index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26,752 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/demos/tcpecho/server.py | 15,17 | 14,31 | handle_stream | EchoServer | 17,31 | 17,31 | class EchoServer(TCPServer):
@gen.coroutine
def handle_stream(self, stream, address):
FILL_FUNC_BODY | class EchoServer(TCPServer):
@gen.coroutine
def handle_stream(self, stream, address):
FILL_FUNC_BODY | while True:
try:
data = yield stream.read_until(b"\n")
logger.info("Received bytes: %s", data)
if not data.endswith(b"\n"):
data = data + b"\n"
yield stream.write(data)
except StreamClosedError:
... | while True:
try:
data = yield stream.read_until(b"\n")
logger.info("Received bytes: %s", data)
if not data.endswith(b"\n"):
data = data + b"\n"
yield stream.write(data)
except StreamClosedError:
... | 35 | 41 | 134 | 175 | #!/usr/bin/env python
import asyncio
import logging
from tornado import gen
from tornado.iostream import StreamClosedError
from tornado.tcpserver import TCPServer
from tornado.options import options, define
define("port", default=9888, help="TCP port to listen on")
logger = logging.getLogger(__name__)
class EchoSer... | #!/usr/bin/env python
import asyncio
import logging
from tornado import gen
from tornado.iostream import StreamClosedError
from tornado.tcpserver import TCPServer
from tornado.options import options, define
define("port", default=9888, help="TCP port to listen on")
logger = logging.getLogger(__name__)
class EchoSer... |
26,753 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/demos/websocket/chatdemo.py | 91,92 | 1,100 | main | 92,98 | 92,98 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... | tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
await asyncio.Event().wait()
| tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
await asyncio.Event().wait()
| 7 | 876 | 47 | 923 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... | |
26,754 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/demos/websocket/chatdemo.py | 61,62 | 49,91 | on_close | ChatSocketHandler | 62,64 | 62,64 | class ChatSocketHandler(tornado.websocket.WebSocketHandler):
waiters = set()
cache = []
cache_size = 200
def get_compression_options(self):
# Non-None enables compression with default options.
return {}
def open(self):
ChatSocketHandler.waiters.add(self)
def on_close(s... | class ChatSocketHandler(tornado.websocket.WebSocketHandler):
waiters = set()
cache = []
cache_size = 200
def get_compression_options(self):
# Non-None enables compression with default options.
return {}
def open(self):
ChatSocketHandler.waiters.add(self)
def on_close(s... | ChatSocketHandler.waiters.remove(self)
| ChatSocketHandler.waiters.remove(self)
| 1 | 384 | 16 | 400 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... |
26,755 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/demos/websocket/chatdemo.py | 45,46 | 44,49 | get | MainHandler | 46,49 | 46,49 | class MainHandler(tornado.web.RequestHandler):
def get(self):
FILL_FUNC_BODY | class MainHandler(tornado.web.RequestHandler):
def get(self):
FILL_FUNC_BODY | self.render("index.html", messages=ChatSocketHandler.cache)
| self.render("index.html", messages=ChatSocketHandler.cache)
| 2 | 31 | 23 | 54 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 a... |
26,756 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/demos/webspider/webspider.py | 51,52 | 1,99 | main | 52,97 | 52,97 | #!/usr/bin/env python3
import asyncio
import time
from datetime import timedelta
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import gen, httpclient, queues
base_url = "http://www.tornadoweb.org/en/stable/"
concurrency = 10
async def get_links_from_url(url):
"""D... | #!/usr/bin/env python3
import asyncio
import time
from datetime import timedelta
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import gen, httpclient, queues
base_url = "http://www.tornadoweb.org/en/stable/"
concurrency = 10
async def get_links_from_url(url):
"""D... | q = queues.Queue()
start = time.time()
fetching, fetched, dead = set(), set(), set()
async def fetch_url(current_url):
if current_url in fetching:
return
print("fetching %s" % current_url)
fetching.add(current_url)
urls = await get_links_from_url(current_url... | q = queues.Queue()
start = time.time()
fetching, fetched, dead = set(), set(), set()
async def fetch_url(current_url):
if current_url in fetching:
return
print("fetching %s" % current_url)
fetching.add(current_url)
urls = await get_links_from_url(current_url... | 139 | 461 | 455 | 916 | #!/usr/bin/env python3
import asyncio
import time
from datetime import timedelta
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import gen, httpclient, queues
base_url = "http://www.tornadoweb.org/en/stable/"
concurrency = 10
async def get_links_from_url(url):
"""D... | #!/usr/bin/env python3
import asyncio
import time
from datetime import timedelta
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import gen, httpclient, queues
base_url = "http://www.tornadoweb.org/en/stable/"
concurrency = 10
async def get_links_from_url(url):
"""D... | |
26,757 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/demos/webspider/webspider.py | 41,42 | 36,46 | handle_starttag | URLSeeker | 42,46 | 42,46 | class URLSeeker(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.urls = []
def handle_starttag(self, tag, attrs):
FILL_FUNC_BODY | class URLSeeker(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.urls = []
def handle_starttag(self, tag, attrs):
FILL_FUNC_BODY | href = dict(attrs).get("href")
if href and tag == "a":
self.urls.append(href)
| href = dict(attrs).get("href")
if href and tag == "a":
self.urls.append(href)
| 10 | 61 | 39 | 100 | #!/usr/bin/env python3
import asyncio
import time
from datetime import timedelta
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import gen, httpclient, queues
base_url = "http://www.tornadoweb.org/en/stable/"
concurrency = 10
async def get_links_from_url(url):
"""D... | #!/usr/bin/env python3
import asyncio
import time
from datetime import timedelta
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag
from tornado import gen, httpclient, queues
base_url = "http://www.tornadoweb.org/en/stable/"
concurrency = 10
async def get_links_from_url(url):
"""D... |
26,758 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/docs/conf.py | 140,141 | 1,147 | missing_reference_handler | 141,145 | 141,145 | import os
import sphinx.errors
import sys
import sphinx_rtd_theme
# Ensure we get the local copy of tornado instead of what's on the standard path
sys.path.insert(0, os.path.abspath(".."))
import tornado
master_doc = "index"
project = "Tornado"
copyright = "The Tornado Authors"
version = release = tornado.version
... | import os
import sphinx.errors
import sys
import sphinx_rtd_theme
# Ensure we get the local copy of tornado instead of what's on the standard path
sys.path.insert(0, os.path.abspath(".."))
import tornado
master_doc = "index"
project = "Tornado"
copyright = "The Tornado Authors"
version = release = tornado.version
... | if node["reftarget"] in missing_references:
raise sphinx.errors.NoUri
| if node["reftarget"] in missing_references:
raise sphinx.errors.NoUri
| 6 | 1,318 | 31 | 1,349 | import os
import sphinx.errors
import sys
import sphinx_rtd_theme
# Ensure we get the local copy of tornado instead of what's on the standard path
sys.path.insert(0, os.path.abspath(".."))
import tornado
master_doc = "index"
project = "Tornado"
copyright = "The Tornado Authors"
version = release = tornado.version
... | import os
import sphinx.errors
import sys
import sphinx_rtd_theme
# Ensure we get the local copy of tornado instead of what's on the standard path
sys.path.insert(0, os.path.abspath(".."))
import tornado
master_doc = "index"
project = "Tornado"
copyright = "The Tornado Authors"
version = release = tornado.version
... | |
26,759 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/maint/benchmark/benchmark.py | 55,56 | 1,74 | run | 56,72 | 56,72 | #!/usr/bin/env python
#
# A simple benchmark of tornado's HTTP stack.
# Requires 'ab' to be installed.
#
# Running without profiling:
# demos/benchmark/benchmark.py
# demos/benchmark/benchmark.py --quiet --num_runs=5|grep "Requests per second"
#
# Running with profiling:
#
# python -m cProfile -o /tmp/prof demos/benchm... | #!/usr/bin/env python
#
# A simple benchmark of tornado's HTTP stack.
# Requires 'ab' to be installed.
#
# Running without profiling:
# demos/benchmark/benchmark.py
# demos/benchmark/benchmark.py --quiet --num_runs=5|grep "Requests per second"
#
# Running with profiling:
#
# python -m cProfile -o /tmp/prof demos/benchm... | app = Application([("/", RootHandler)])
port = random.randrange(options.min_port, options.max_port)
app.listen(port, address="127.0.0.1")
args = ["ab"]
args.extend(["-n", str(options.n)])
args.extend(["-c", str(options.c)])
if options.keepalive:
args.append("-k")
if options.quiet... | app = Application([("/", RootHandler)])
port = random.randrange(options.min_port, options.max_port)
app.listen(port, address="127.0.0.1")
args = ["ab"]
args.extend(["-n", str(options.n)])
args.extend(["-c", str(options.c)])
if options.keepalive:
args.append("-k")
if options.quiet... | 41 | 513 | 207 | 720 | #!/usr/bin/env python
#
# A simple benchmark of tornado's HTTP stack.
# Requires 'ab' to be installed.
#
# Running without profiling:
# demos/benchmark/benchmark.py
# demos/benchmark/benchmark.py --quiet --num_runs=5|grep "Requests per second"
#
# Running with profiling:
#
# python -m cProfile -o /tmp/prof demos/benchm... | #!/usr/bin/env python
#
# A simple benchmark of tornado's HTTP stack.
# Requires 'ab' to be installed.
#
# Running without profiling:
# demos/benchmark/benchmark.py
# demos/benchmark/benchmark.py --quiet --num_runs=5|grep "Requests per second"
#
# Running with profiling:
#
# python -m cProfile -o /tmp/prof demos/benchm... | |
26,760 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/maint/benchmark/benchmark.py | 42,43 | 41,49 | get | RootHandler | 43,45 | 43,45 | class RootHandler(RequestHandler):
def get(self):
FILL_FUNC_BODY def _log(self):
pass
| class RootHandler(RequestHandler):
def get(self):
FILL_FUNC_BODY def _log(self):
pass
| self.write("Hello, world")
| self.write("Hello, world")
| 2 | 38 | 13 | 51 | #!/usr/bin/env python
#
# A simple benchmark of tornado's HTTP stack.
# Requires 'ab' to be installed.
#
# Running without profiling:
# demos/benchmark/benchmark.py
# demos/benchmark/benchmark.py --quiet --num_runs=5|grep "Requests per second"
#
# Running with profiling:
#
# python -m cProfile -o /tmp/prof demos/benchm... | #!/usr/bin/env python
#
# A simple benchmark of tornado's HTTP stack.
# Requires 'ab' to be installed.
#
# Running without profiling:
# demos/benchmark/benchmark.py
# demos/benchmark/benchmark.py --quiet --num_runs=5|grep "Requests per second"
#
# Running with profiling:
#
# python -m cProfile -o /tmp/prof demos/benchm... |
26,761 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/maint/benchmark/template_benchmark.py | 56,57 | 1,72 | render | 57,60 | 57,60 | #!/usr/bin/env python
#
# A simple benchmark of tornado template rendering, based on
# https://github.com/mitsuhiko/jinja2/blob/master/examples/bench.py
import sys
from timeit import Timer
from tornado.options import options, define, parse_command_line
from tornado.template import Template
define('num', default=100,... | #!/usr/bin/env python
#
# A simple benchmark of tornado template rendering, based on
# https://github.com/mitsuhiko/jinja2/blob/master/examples/bench.py
import sys
from timeit import Timer
from tornado.options import options, define, parse_command_line
from tornado.template import Template
define('num', default=100,... | tmpl.generate(**context)
| tmpl.generate(**context)
| 1 | 578 | 15 | 593 | #!/usr/bin/env python
#
# A simple benchmark of tornado template rendering, based on
# https://github.com/mitsuhiko/jinja2/blob/master/examples/bench.py
import sys
from timeit import Timer
from tornado.options import options, define, parse_command_line
from tornado.template import Template
define('num', default=100,... | #!/usr/bin/env python
#
# A simple benchmark of tornado template rendering, based on
# https://github.com/mitsuhiko/jinja2/blob/master/examples/bench.py
import sys
from timeit import Timer
from tornado.options import options, define, parse_command_line
from tornado.template import Template
define('num', default=100,... | |
26,762 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/maint/scripts/custom_fixers/fix_future_imports.py | 10,11 | 1,60 | is_docstring | 11,14 | 11,14 | """Updates all source files to import the same set of __future__ directives.
"""
from lib2to3 import fixer_base
from lib2to3 import pytree
from lib2to3.pgen2 import token
from lib2to3.fixer_util import FromImport, Name, Comma, Newline
# copied from fix_tuple_params.py
def is_docstring(stmt):
FILL_FUNC_BODYclass FixFu... | """Updates all source files to import the same set of __future__ directives.
"""
from lib2to3 import fixer_base
from lib2to3 import pytree
from lib2to3.pgen2 import token
from lib2to3.fixer_util import FromImport, Name, Comma, Newline
# copied from fix_tuple_params.py
def is_docstring(stmt):
FILL_FUNC_BODYclass FixFu... | return isinstance(stmt, pytree.Node) and stmt.children[0].type == token.STRING
| return isinstance(stmt, pytree.Node) and stmt.children[0].type == token.STRING
| 7 | 601 | 31 | 632 | """Updates all source files to import the same set of __future__ directives.
"""
from lib2to3 import fixer_base
from lib2to3 import pytree
from lib2to3.pgen2 import token
from lib2to3.fixer_util import FromImport, Name, Comma, Newline
# copied from fix_tuple_params.py
def is_docstring(stmt):
FILL_FUNC_BODYclass FixFu... | """Updates all source files to import the same set of __future__ directives.
"""
from lib2to3 import fixer_base
from lib2to3 import pytree
from lib2to3.pgen2 import token
from lib2to3.fixer_util import FromImport, Name, Comma, Newline
# copied from fix_tuple_params.py
def is_docstring(stmt):
FILL_FUNC_BODYclass FixFu... | |
26,763 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/maint/scripts/custom_fixers/fix_future_imports.py | 22,23 | 14,60 | new_future_import | FixFutureImports | 23,31 | 23,31 | class FixFutureImports(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """import_from< 'from' module_name="__future__" 'import' any >"""
def start_tree(self, tree, filename):
self.found_future_import = False
def new_future_import(self, old):
FILL_FUNC_BODY def transform(self, node, res... | class FixFutureImports(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """import_from< 'from' module_name="__future__" 'import' any >"""
def start_tree(self, tree, filename):
self.found_future_import = False
def new_future_import(self, old):
FILL_FUNC_BODY def transform(self, node, res... | new = FromImport("__future__",
[Name("absolute_import", prefix=" "), Comma(),
Name("division", prefix=" "), Comma(),
Name("print_function", prefix=" ")])
if old is not None:
new.prefix = old.prefix
return ne... | new = FromImport("__future__",
[Name("absolute_import", prefix=" "), Comma(),
Name("division", prefix=" "), Comma(),
Name("print_function", prefix=" ")])
if old is not None:
new.prefix = old.prefix
return ne... | 24 | 425 | 86 | 511 | """Updates all source files to import the same set of __future__ directives.
"""
from lib2to3 import fixer_base
from lib2to3 import pytree
from lib2to3.pgen2 import token
from lib2to3.fixer_util import FromImport, Name, Comma, Newline
# copied from fix_tuple_params.py
def is_docstring(stmt):
return isinstance(stm... | """Updates all source files to import the same set of __future__ directives.
"""
from lib2to3 import fixer_base
from lib2to3 import pytree
from lib2to3.pgen2 import token
from lib2to3.fixer_util import FromImport, Name, Comma, Newline
# copied from fix_tuple_params.py
def is_docstring(stmt):
return isinstance(stm... |
26,764 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/maint/scripts/custom_fixers/fix_unicode_literal.py | 17,18 | 5,20 | transform | FixUnicodeLiteral | 18,20 | 18,20 | class FixUnicodeLiteral(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< 'u'
trailer<
'('
arg=any
')'
>
>
"""
def transform(self, node, results):
FILL_FUNC_BODY | class FixUnicodeLiteral(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< 'u'
trailer<
'('
arg=any
')'
>
>
"""
def transform(self, node, results):
FILL_FUNC_BODY | arg = results["arg"]
node.replace(String('u' + arg.value, prefix=node.prefix))
| arg = results["arg"]
node.replace(String('u' + arg.value, prefix=node.prefix))
| 7 | 85 | 31 | 116 | from lib2to3 import fixer_base
from lib2to3.fixer_util import String
class FixUnicodeLiteral(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< 'u'
trailer<
'('
arg=any
')'
>
>
"""
def transform(self, node, results):
FILL_FUN... | from lib2to3 import fixer_base
from lib2to3.fixer_util import String
class FixUnicodeLiteral(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< 'u'
trailer<
'('
arg=any
')'
>
>
"""
def transform(self, node, results):
FILL_FUN... |
26,765 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/maint/scripts/test_resolvers.py | 24,26 | 1,59 | main | 26,57 | 26,57 | #!/usr/bin/env python
import pprint
import socket
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.netutil import Resolver, ThreadedResolver, DefaultExecutorResolver
from tornado.options import parse_command_line, define, options
try:
import twisted
except ImportError:
twisted = None
tr... | #!/usr/bin/env python
import pprint
import socket
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.netutil import Resolver, ThreadedResolver, DefaultExecutorResolver
from tornado.options import parse_command_line, define, options
try:
import twisted
except ImportError:
twisted = None
tr... | args = parse_command_line()
if not args:
args = ['localhost', 'www.google.com',
'www.facebook.com', 'www.dropbox.com']
resolvers = [Resolver(), ThreadedResolver(), DefaultExecutorResolver()]
if twisted is not None:
from tornado.platform.twisted import TwistedResolver
... | args = parse_command_line()
if not args:
args = ['localhost', 'www.google.com',
'www.facebook.com', 'www.dropbox.com']
resolvers = [Resolver(), ThreadedResolver(), DefaultExecutorResolver()]
if twisted is not None:
from tornado.platform.twisted import TwistedResolver
... | 71 | 189 | 310 | 499 | #!/usr/bin/env python
import pprint
import socket
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.netutil import Resolver, ThreadedResolver, DefaultExecutorResolver
from tornado.options import parse_command_line, define, options
try:
import twisted
except ImportError:
twisted = None
tr... | #!/usr/bin/env python
import pprint
import socket
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.netutil import Resolver, ThreadedResolver, DefaultExecutorResolver
from tornado.options import parse_command_line, define, options
try:
import twisted
except ImportError:
twisted = None
tr... | |
26,766 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/setup.py | 62,63 | 61,69 | get_tag | bdist_wheel_abi3 | 63,69 | 63,69 | class bdist_wheel_abi3(wheel.bdist_wheel.bdist_wheel):
def get_tag(self):
FILL_FUNC_BODY | class bdist_wheel_abi3(wheel.bdist_wheel.bdist_wheel):
def get_tag(self):
FILL_FUNC_BODY | python, abi, plat = super().get_tag()
if python.startswith("cp"):
return "cp38", "abi3", plat
return python, abi, plat
| python, abi, plat = super().get_tag()
if python.startswith("cp"):
return "cp38", "abi3", plat
return python, abi, plat
| 15 | 42 | 57 | 99 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,768 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/auth.py | 1004,1012 | 996,1177 | get_authenticated_user | FacebookGraphMixin | 1060,1114 | 1012,1114 | class FacebookGraphMixin(OAuth2Mixin):
"""Facebook authentication using the new Graph API and OAuth2."""
_OAUTH_ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token?"
_OAUTH_AUTHORIZE_URL = "https://www.facebook.com/dialog/oauth?"
_OAUTH_NO_CALLBACKS = False
_FACEBOOK_BASE_URL = "https... | class FacebookGraphMixin(OAuth2Mixin):
"""Facebook authentication using the new Graph API and OAuth2."""
_OAUTH_ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token?"
_OAUTH_AUTHORIZE_URL = "https://www.facebook.com/dialog/oauth?"
_OAUTH_NO_CALLBACKS = False
_FACEBOOK_BASE_URL = "https... | http = self.get_auth_http_client()
args = {
"redirect_uri": redirect_uri,
"code": code,
"client_id": client_id,
"client_secret": client_secret,
}
fields = set(
["id", "name", "first_name", "last_name", "locale", "picture", "lin... | """Handles the login for the Facebook user, returning a user object.
Example usage:
.. testcode::
class FacebookGraphLoginHandler(tornado.web.RequestHandler,
tornado.auth.FacebookGraphMixin):
async def get(self):
... | 127 | 1,366 | 527 | 1,893 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,769 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/auth.py | 909,916 | 863,996 | get_authenticated_user | GoogleOAuth2Mixin | 968,996 | 916,996 | class GoogleOAuth2Mixin(OAuth2Mixin):
"""Google authentication using OAuth2.
In order to use, register your application with Google and copy the
relevant parameters to your application settings.
* Go to the Google Dev Console at http://console.developers.google.com
* Select a project, or create a ... | class GoogleOAuth2Mixin(OAuth2Mixin):
"""Google authentication using OAuth2.
In order to use, register your application with Google and copy the
relevant parameters to your application settings.
* Go to the Google Dev Console at http://console.developers.google.com
* Select a project, or create a ... | """ # noqa: E501
if client_id is None or client_secret is None:
settings = self.get_google_oauth_settings()
if client_id is None:
client_id = settings["key"]
if client_secret is None:
client_secret = settings["secret"]
http = ... | """Handles the login for the Google user, returning an access token.
The result is a dictionary containing an ``access_token`` field
([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).
Unlike other ``get_authenticated_user`` methods in... | 60 | 1,280 | 281 | 1,561 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,770 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/auth.py | 611,619 | 558,700 | _oauth_request_token_url | OAuth2Mixin | 619,633 | 619,633 | class OAuth2Mixin(object):
"""Abstract implementation of OAuth 2.0.
See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example
implementations.
Class attributes:
* ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.
* ``_OAUTH_ACCESS_TOKEN_URL``: The service's access token url.... | class OAuth2Mixin(object):
"""Abstract implementation of OAuth 2.0.
See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example
implementations.
Class attributes:
* ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.
* ``_OAUTH_ACCESS_TOKEN_URL``: The service's access token url.... | url = self._OAUTH_ACCESS_TOKEN_URL # type: ignore
args = {} # type: Dict[str, str]
if redirect_uri is not None:
args["redirect_uri"] = redirect_uri
if code is not None:
args["code"] = code
if client_id is not None:
args["client_id"] = client_... | url = self._OAUTH_ACCESS_TOKEN_URL # type: ignore
args = {} # type: Dict[str, str]
if redirect_uri is not None:
args["redirect_uri"] = redirect_uri
if code is not None:
args["code"] = code
if client_id is not None:
args["client_id"] = client_... | 51 | 1,250 | 165 | 1,415 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,773 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/auth.py | 843,844 | 700,863 | _oauth_consumer_token | TwitterMixin | 844,852 | 844,852 | class TwitterMixin(OAuthMixin):
"""Twitter OAuth authentication.
To authenticate with Twitter, register your application with
Twitter at http://twitter.com/apps. Then copy your Consumer Key
and Consumer Secret to the application
`~tornado.web.Application.settings` ``twitter_consumer_key`` and
`... | class TwitterMixin(OAuthMixin):
"""Twitter OAuth authentication.
To authenticate with Twitter, register your application with
Twitter at http://twitter.com/apps. Then copy your Consumer Key
and Consumer Secret to the application
`~tornado.web.Application.settings` ``twitter_consumer_key`` and
`... | handler = cast(RequestHandler, self)
handler.require_setting("twitter_consumer_key", "Twitter OAuth")
handler.require_setting("twitter_consumer_secret", "Twitter OAuth")
return dict(
key=handler.settings["twitter_consumer_key"],
secret=handler.settings["twitter_co... | handler = cast(RequestHandler, self)
handler.require_setting("twitter_consumer_key", "Twitter OAuth")
handler.require_setting("twitter_consumer_secret", "Twitter OAuth")
return dict(
key=handler.settings["twitter_consumer_key"],
secret=handler.settings["twitter_co... | 15 | 1,712 | 100 | 1,812 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,775 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/concurrent.py | 57,60 | 56,78 | submit | DummyExecutor | 60,67 | 60,67 | class DummyExecutor(futures.Executor):
def submit( # type: ignore[override]
self, fn: Callable[..., _T], *args: Any, **kwargs: Any
) -> "futures.Future[_T]":
FILL_FUNC_BODY if sys.version_info >= (3, 9):
def shutdown(self, wait: bool = True, cancel_futures: bool = False) -> None:
... | class DummyExecutor(futures.Executor):
def submit( # type: ignore[override]
self, fn: Callable[..., _T], *args: Any, **kwargs: Any
) -> "futures.Future[_T]":
FILL_FUNC_BODY if sys.version_info >= (3, 9):
def shutdown(self, wait: bool = True, cancel_futures: bool = False) -> None:
... | future = futures.Future() # type: futures.Future[_T]
try:
future_set_result_unless_cancelled(future, fn(*args, **kwargs))
except Exception:
future_set_exc_info(future, sys.exc_info())
return future
| future = futures.Future() # type: futures.Future[_T]
try:
future_set_result_unless_cancelled(future, fn(*args, **kwargs))
except Exception:
future_set_exc_info(future, sys.exc_info())
return future
| 16 | 149 | 83 | 232 | #
# Copyright 2012 Facebook
#
# 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, s... | #
# Copyright 2012 Facebook
#
# 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, s... |
26,778 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/gen.py | 808,809 | 723,843 | handle_yield | Runner | 809,831 | 809,831 | class Runner(object):
"""Internal implementation of `tornado.gen.coroutine`.
Maintains information about pending callbacks and their results.
The results of the generator are stored in ``result_future`` (a
`.Future`)
"""
def __init__(
self,
ctx_run: Callable,
gen: "Gen... | class Runner(object):
"""Internal implementation of `tornado.gen.coroutine`.
Maintains information about pending callbacks and their results.
The results of the generator are stored in ``result_future`` (a
`.Future`)
"""
def __init__(
self,
ctx_run: Callable,
gen: "Gen... | try:
self.future = convert_yielded(yielded)
except BadYieldError:
self.future = Future()
future_set_exc_info(self.future, sys.exc_info())
if self.future is moment:
self.io_loop.add_callback(self.ctx_run, self.run)
return False
... | try:
self.future = convert_yielded(yielded)
except BadYieldError:
self.future = Future()
future_set_exc_info(self.future, sys.exc_info())
if self.future is moment:
self.io_loop.add_callback(self.ctx_run, self.run)
return False
... | 56 | 865 | 222 | 1,087 | """``tornado.gen`` implements generator-based coroutines.
.. note::
The "decorator and generator" approach in this module is a
precursor to native coroutines (using ``async def`` and ``await``)
which were introduced in Python 3.5. Applications that do not
require compatibility with older versions of Pytho... | """``tornado.gen`` implements generator-based coroutines.
.. note::
The "decorator and generator" approach in this module is a
precursor to native coroutines (using ``async def`` and ``await``)
which were introduced in Python 3.5. Applications that do not
require compatibility with older versions of Pytho... |
26,779 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/gen.py | 386,387 | 310,438 | done | WaitIterator | 388,394 | 387,394 | class WaitIterator(object):
"""Provides an iterator to yield the results of awaitables as they finish.
Yielding a set of awaitables like this:
``results = yield [awaitable1, awaitable2]``
pauses the coroutine until both ``awaitable1`` and ``awaitable2``
return, and then restarts the coroutine wit... | class WaitIterator(object):
"""Provides an iterator to yield the results of awaitables as they finish.
Yielding a set of awaitables like this:
``results = yield [awaitable1, awaitable2]``
pauses the coroutine until both ``awaitable1`` and ``awaitable2``
return, and then restarts the coroutine wit... | if self._finished or self._unfinished:
return False
# Clear the 'current' values when iteration is done.
self.current_index = self.current_future = None
return True
| """Returns True if this iterator has no more results."""
if self._finished or self._unfinished:
return False
# Clear the 'current' values when iteration is done.
self.current_index = self.current_future = None
return True
| 22 | 1,259 | 55 | 1,314 | """``tornado.gen`` implements generator-based coroutines.
.. note::
The "decorator and generator" approach in this module is a
precursor to native coroutines (using ``async def`` and ``await``)
which were introduced in Python 3.5. Applications that do not
require compatibility with older versions of Pytho... | """``tornado.gen`` implements generator-based coroutines.
.. note::
The "decorator and generator" approach in this module is a
precursor to native coroutines (using ``async def`` and ``await``)
which were introduced in Python 3.5. Applications that do not
require compatibility with older versions of Pytho... |
26,780 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/gen.py | 694,695 | 678,701 | done | _NullFuture | 695,701 | 695,701 | class _NullFuture(object):
"""_NullFuture resembles a Future that finished with a result of None.
It's not actually a `Future` to avoid depending on a particular event loop.
Handled as a special case in the coroutine runner.
We lie and tell the type checker that a _NullFuture is a Future so
we don... | class _NullFuture(object):
"""_NullFuture resembles a Future that finished with a result of None.
It's not actually a `Future` to avoid depending on a particular event loop.
Handled as a special case in the coroutine runner.
We lie and tell the type checker that a _NullFuture is a Future so
we don... | return True
# _null_future is used as a dummy value in the coroutine runner. It differs
# from moment in that moment always adds a delay of one IOLoop iteration
# while _null_future is processed as soon as possible.
| return True
# _null_future is used as a dummy value in the coroutine runner. It differs
# from moment in that moment always adds a delay of one IOLoop iteration
# while _null_future is processed as soon as possible.
| 39 | 185 | 66 | 251 | """``tornado.gen`` implements generator-based coroutines.
.. note::
The "decorator and generator" approach in this module is a
precursor to native coroutines (using ``async def`` and ``await``)
which were introduced in Python 3.5. Applications that do not
require compatibility with older versions of Pytho... | """``tornado.gen`` implements generator-based coroutines.
.. note::
The "decorator and generator" approach in this module is a
precursor to native coroutines (using ``async def`` and ``await``)
which were introduced in Python 3.5. Applications that do not
require compatibility with older versions of Pytho... |
26,783 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/http1connection.py | 820,823 | 773,850 | _server_request_loop | HTTP1ServerConnection | 823,850 | 823,850 | class HTTP1ServerConnection(object):
"""An HTTP/1.x server."""
def __init__(
self,
stream: iostream.IOStream,
params: Optional[HTTP1ConnectionParameters] = None,
context: Optional[object] = None,
) -> None:
"""
:arg stream: an `.IOStream`
:arg params:... | class HTTP1ServerConnection(object):
"""An HTTP/1.x server."""
def __init__(
self,
stream: iostream.IOStream,
params: Optional[HTTP1ConnectionParameters] = None,
context: Optional[object] = None,
) -> None:
"""
:arg stream: an `.IOStream`
:arg params:... | try:
while True:
conn = HTTP1Connection(self.stream, False, self.params, self.context)
request_delegate = delegate.start_request(self, conn)
try:
ret = await conn.read_response(request_delegate)
except (
... | try:
while True:
conn = HTTP1Connection(self.stream, False, self.params, self.context)
request_delegate = delegate.start_request(self, conn)
try:
ret = await conn.read_response(request_delegate)
except (
... | 50 | 507 | 235 | 742 | #
# Copyright 2014 Facebook
#
# 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, s... | #
# Copyright 2014 Facebook
#
# 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, s... |
26,784 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/http1connection.py | 733,734 | 711,773 | data_received | _GzipMessageDelegate | 734,754 | 734,754 | class _GzipMessageDelegate(httputil.HTTPMessageDelegate):
"""Wraps an `HTTPMessageDelegate` to decode ``Content-Encoding: gzip``."""
def __init__(self, delegate: httputil.HTTPMessageDelegate, chunk_size: int) -> None:
self._delegate = delegate
self._chunk_size = chunk_size
self._decompr... | class _GzipMessageDelegate(httputil.HTTPMessageDelegate):
"""Wraps an `HTTPMessageDelegate` to decode ``Content-Encoding: gzip``."""
def __init__(self, delegate: httputil.HTTPMessageDelegate, chunk_size: int) -> None:
self._delegate = delegate
self._chunk_size = chunk_size
self._decompr... | if self._decompressor:
compressed_data = chunk
while compressed_data:
decompressed = self._decompressor.decompress(
compressed_data, self._chunk_size
)
if decompressed:
ret = self._delegate.data_recei... | if self._decompressor:
compressed_data = chunk
while compressed_data:
decompressed = self._decompressor.decompress(
compressed_data, self._chunk_size
)
if decompressed:
ret = self._delegate.data_recei... | 54 | 529 | 203 | 732 | #
# Copyright 2014 Facebook
#
# 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, s... | #
# Copyright 2014 Facebook
#
# 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, s... |
26,787 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httpclient.py | 104,105 | 59,140 | make_client | HTTPClient | 105,109 | 105,109 | class HTTPClient(object):
"""A blocking HTTP client.
This interface is provided to make it easier to share code between
synchronous and asynchronous applications. Applications that are
running an `.IOLoop` must use `AsyncHTTPClient` instead.
Typical usage looks like this::
http_client = h... | class HTTPClient(object):
"""A blocking HTTP client.
This interface is provided to make it easier to share code between
synchronous and asynchronous applications. Applications that are
running an `.IOLoop` must use `AsyncHTTPClient` instead.
Typical usage looks like this::
http_client = h... | await gen.sleep(0)
assert async_client_class is not None
return async_client_class(**kwargs)
| await gen.sleep(0)
assert async_client_class is not None
return async_client_class(**kwargs)
| 9 | 759 | 37 | 796 | """Blocking and non-blocking HTTP client interfaces.
This module defines a common interface shared by two implementations,
``simple_httpclient`` and ``curl_httpclient``. Applications may either
instantiate their chosen implementation class directly or use the
`AsyncHTTPClient` class from this module, which selects an... | """Blocking and non-blocking HTTP client interfaces.
This module defines a common interface shared by two implementations,
``simple_httpclient`` and ``curl_httpclient``. Applications may either
instantiate their chosen implementation class directly or use the
`AsyncHTTPClient` class from this module, which selects an... |
26,789 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httpclient.py | 671,673 | 574,690 | body | HTTPResponse | 673,680 | 673,680 | class HTTPResponse(object):
"""HTTP Response object.
Attributes:
* ``request``: HTTPRequest object
* ``code``: numeric HTTP status code, e.g. 200 or 404
* ``reason``: human-readable reason phrase describing the status code
* ``headers``: `tornado.httputil.HTTPHeaders` object
* ``effect... | class HTTPResponse(object):
"""HTTP Response object.
Attributes:
* ``request``: HTTPRequest object
* ``code``: numeric HTTP status code, e.g. 200 or 404
* ``reason``: human-readable reason phrase describing the status code
* ``headers``: `tornado.httputil.HTTPHeaders` object
* ``effect... | if self.buffer is None:
return b""
elif self._body is None:
self._body = self.buffer.getvalue()
return self._body
| if self.buffer is None:
return b""
elif self._body is None:
self._body = self.buffer.getvalue()
return self._body
| 15 | 1,145 | 51 | 1,196 | """Blocking and non-blocking HTTP client interfaces.
This module defines a common interface shared by two implementations,
``simple_httpclient`` and ``curl_httpclient``. Applications may either
instantiate their chosen implementation class directly or use the
`AsyncHTTPClient` class from this module, which selects an... | """Blocking and non-blocking HTTP client interfaces.
This module defines a common interface shared by two implementations,
``simple_httpclient`` and ``curl_httpclient``. Applications may either
instantiate their chosen implementation class directly or use the
`AsyncHTTPClient` class from this module, which selects an... |
26,791 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httpserver.py | 272,277 | 260,298 | headers_received | _CallableAdapter | 277,284 | 277,284 | class _CallableAdapter(httputil.HTTPMessageDelegate):
def __init__(
self,
request_callback: Callable[[httputil.HTTPServerRequest], None],
request_conn: httputil.HTTPConnection,
) -> None:
self.connection = request_conn
self.request_callback = request_callback
self... | class _CallableAdapter(httputil.HTTPMessageDelegate):
def __init__(
self,
request_callback: Callable[[httputil.HTTPServerRequest], None],
request_conn: httputil.HTTPConnection,
) -> None:
self.connection = request_conn
self.request_callback = request_callback
self... | self.request = httputil.HTTPServerRequest(
connection=self.connection,
start_line=typing.cast(httputil.RequestStartLine, start_line),
headers=headers,
)
return None
| self.request = httputil.HTTPServerRequest(
connection=self.connection,
start_line=typing.cast(httputil.RequestStartLine, start_line),
headers=headers,
)
return None
| 10 | 331 | 68 | 399 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,792 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httpserver.py | 344,345 | 298,376 | _apply_xheaders | _HTTPRequestContext | 346,366 | 345,366 | class _HTTPRequestContext(object):
def __init__(
self,
stream: iostream.IOStream,
address: Tuple,
protocol: Optional[str],
trusted_downstream: Optional[List[str]] = None,
) -> None:
self.address = address
# Save the socket's address family now so we know h... | class _HTTPRequestContext(object):
def __init__(
self,
stream: iostream.IOStream,
address: Tuple,
protocol: Optional[str],
trusted_downstream: Optional[List[str]] = None,
) -> None:
self.address = address
# Save the socket's address family now so we know h... | # Squid uses X-Forwarded-For, others use X-Real-Ip
ip = headers.get("X-Forwarded-For", self.remote_ip)
# Skip trusted downstream hosts in X-Forwarded-For list
for ip in (cand.strip() for cand in reversed(ip.split(","))):
if ip not in self.trusted_downstream:
b... | """Rewrite the ``remote_ip`` and ``protocol`` fields."""
# Squid uses X-Forwarded-For, others use X-Real-Ip
ip = headers.get("X-Forwarded-For", self.remote_ip)
# Skip trusted downstream hosts in X-Forwarded-For list
for ip in (cand.strip() for cand in reversed(ip.split(","))):
... | 88 | 620 | 293 | 913 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,793 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httpserver.py | 385,390 | 376,410 | headers_received | _ProxyAdapter | 390,395 | 390,395 | class _ProxyAdapter(httputil.HTTPMessageDelegate):
def __init__(
self,
delegate: httputil.HTTPMessageDelegate,
request_conn: httputil.HTTPConnection,
) -> None:
self.connection = request_conn
self.delegate = delegate
def headers_received(
self,
start_... | class _ProxyAdapter(httputil.HTTPMessageDelegate):
def __init__(
self,
delegate: httputil.HTTPMessageDelegate,
request_conn: httputil.HTTPConnection,
) -> None:
self.connection = request_conn
self.delegate = delegate
def headers_received(
self,
start_... | # TODO: either make context an official part of the
# HTTPConnection interface or figure out some other way to do this.
self.connection.context._apply_xheaders(headers) # type: ignore
return self.delegate.headers_received(start_line, headers)
| # TODO: either make context an official part of the
# HTTPConnection interface or figure out some other way to do this.
self.connection.context._apply_xheaders(headers) # type: ignore
return self.delegate.headers_received(start_line, headers)
| 29 | 287 | 74 | 361 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,795 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httputil.py | 569,575 | 563,609 | write_headers | HTTPConnection | 591,593 | 575,593 | class HTTPConnection(object):
"""Applications use this interface to write their responses.
.. versionadded:: 4.0
"""
def write_headers(
self,
start_line: Union["RequestStartLine", "ResponseStartLine"],
headers: HTTPHeaders,
chunk: Optional[bytes] = None,
) -> "Futur... | class HTTPConnection(object):
"""Applications use this interface to write their responses.
.. versionadded:: 4.0
"""
def write_headers(
self,
start_line: Union["RequestStartLine", "ResponseStartLine"],
headers: HTTPHeaders,
chunk: Optional[bytes] = None,
) -> "Futur... | raise NotImplementedError()
| """Write an HTTP header block.
:arg start_line: a `.RequestStartLine` or `.ResponseStartLine`.
:arg headers: a `.HTTPHeaders` instance.
:arg chunk: the first (optional) chunk of data. This is an optimization
so that small responses can be written in the same call as their
... | 2 | 352 | 12 | 364 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,796 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httputil.py | 229,230 | 76,247 | copy | HTTPHeaders | 230,236 | 230,236 | class HTTPHeaders(collections.abc.MutableMapping):
"""A dictionary that maintains ``Http-Header-Case`` for all keys.
Supports multiple values per key via a pair of new methods,
`add()` and `get_list()`. The regular dictionary interface
returns a single value per key, with multiple values joined by a
... | class HTTPHeaders(collections.abc.MutableMapping):
"""A dictionary that maintains ``Http-Header-Case`` for all keys.
Supports multiple values per key via a pair of new methods,
`add()` and `get_list()`. The regular dictionary interface
returns a single value per key, with multiple values joined by a
... | # defined in dict but not in MutableMapping.
return HTTPHeaders(self)
# Use our overridden copy method for the copy.copy module.
# This makes shallow copies one level deeper, but preserves
# the appearance that HTTPHeaders is a single container.
| # defined in dict but not in MutableMapping.
return HTTPHeaders(self)
# Use our overridden copy method for the copy.copy module.
# This makes shallow copies one level deeper, but preserves
# the appearance that HTTPHeaders is a single container.
| 39 | 1,729 | 72 | 1,801 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,797 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/httputil.py | 494,497 | 488,517 | start_request | HTTPServerConnectionDelegate | 506,508 | 497,508 | class HTTPServerConnectionDelegate(object):
"""Implement this interface to handle requests from `.HTTPServer`.
.. versionadded:: 4.0
"""
def start_request(
self, server_conn: object, request_conn: "HTTPConnection"
) -> "HTTPMessageDelegate":
FILL_FUNC_BODY def on_close(self, server_conn... | class HTTPServerConnectionDelegate(object):
"""Implement this interface to handle requests from `.HTTPServer`.
.. versionadded:: 4.0
"""
def start_request(
self, server_conn: object, request_conn: "HTTPConnection"
) -> "HTTPMessageDelegate":
"""This method is called by the server w... | raise NotImplementedError()
| """This method is called by the server when a new request has started.
:arg server_conn: is an opaque object representing the long-lived
(e.g. tcp-level) connection.
:arg request_conn: is a `.HTTPConnection` object for a single
request/response exchange.
This me... | 2 | 254 | 12 | 266 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,800 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/ioloop.py | 933,934 | 854,979 | _run | PeriodicCallback | 934,945 | 934,945 | class PeriodicCallback(object):
"""Schedules the given callback to be called periodically.
The callback is called every ``callback_time`` milliseconds when
``callback_time`` is a float. Note that the timeout is given in
milliseconds, while most other time-related functions in Tornado use
seconds. `... | class PeriodicCallback(object):
"""Schedules the given callback to be called periodically.
The callback is called every ``callback_time`` milliseconds when
``callback_time`` is a float. Note that the timeout is given in
milliseconds, while most other time-related functions in Tornado use
seconds. `... | if not self._running:
return
try:
val = self.callback()
if val is not None and isawaitable(val):
await val
except Exception:
app_log.error("Exception in callback %r", self.callback, exc_info=True)
finally:
self._... | if not self._running:
return
try:
val = self.callback()
if val is not None and isawaitable(val):
await val
except Exception:
app_log.error("Exception in callback %r", self.callback, exc_info=True)
finally:
self._... | 27 | 1,316 | 96 | 1,412 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,802 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locale.py | 509,516 | 485,521 | pgettext | CSVLocale | 516,521 | 516,521 | class CSVLocale(Locale):
"""Locale implementation using tornado's CSV translation format."""
def __init__(self, code: str, translations: Dict[str, Dict[str, str]]) -> None:
self.translations = translations
super().__init__(code)
def translate(
self,
message: str,
pl... | class CSVLocale(Locale):
"""Locale implementation using tornado's CSV translation format."""
def __init__(self, code: str, translations: Dict[str, Dict[str, str]]) -> None:
self.translations = translations
super().__init__(code)
def translate(
self,
message: str,
pl... | if self.translations:
gen_log.warning("pgettext is not supported by CSVLocale")
return self.translate(message, plural_message, count)
| if self.translations:
gen_log.warning("pgettext is not supported by CSVLocale")
return self.translate(message, plural_message, count)
| 12 | 299 | 51 | 350 | # Copyright 2009 Facebook
#
# 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, sof... | # Copyright 2009 Facebook
#
# 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, sof... |
26,803 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locale.py | 543,550 | 521,588 | pgettext | GettextLocale | 569,588 | 550,588 | class GettextLocale(Locale):
"""Locale implementation using the `gettext` module."""
def __init__(self, code: str, translations: gettext.NullTranslations) -> None:
self.ngettext = translations.ngettext
self.gettext = translations.gettext
# self.gettext must exist before __init__ is call... | class GettextLocale(Locale):
"""Locale implementation using the `gettext` module."""
def __init__(self, code: str, translations: gettext.NullTranslations) -> None:
self.ngettext = translations.ngettext
self.gettext = translations.gettext
# self.gettext must exist before __init__ is call... | if plural_message is not None:
assert count is not None
msgs_with_ctxt = (
"%s%s%s" % (context, CONTEXT_SEPARATOR, message),
"%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message),
count,
)
result = self.ngettext(*m... | """Allows to set context for translation, accepts plural forms.
Usage example::
pgettext("law", "right")
pgettext("good", "right")
Plural message example::
pgettext("organization", "club", "clubs", len(clubs))
pgettext("stick", "club", "clubs",... | 67 | 451 | 236 | 687 | # Copyright 2009 Facebook
#
# 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, sof... | # Copyright 2009 Facebook
#
# 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, sof... |
26,805 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locks.py | 480,481 | 467,487 | release | BoundedSemaphore | 482,487 | 481,487 | class BoundedSemaphore(Semaphore):
"""A semaphore that prevents release() being called too many times.
If `.release` would increment the semaphore's value past the initial
value, it raises `ValueError`. Semaphores are mostly used to guard
resources with limited capacity, so a semaphore released too man... | class BoundedSemaphore(Semaphore):
"""A semaphore that prevents release() being called too many times.
If `.release` would increment the semaphore's value past the initial
value, it raises `ValueError`. Semaphores are mostly used to guard
resources with limited capacity, so a semaphore released too man... | if self._value >= self._initial_value:
raise ValueError("Semaphore released too many times")
super().release()
| """Increment the counter and wake one waiter."""
if self._value >= self._initial_value:
raise ValueError("Semaphore released too many times")
super().release()
| 11 | 171 | 40 | 211 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,806 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locks.py | 119,122 | 53,158 | wait | Condition | 127,141 | 122,141 | class Condition(_TimeoutGarbageCollector):
"""A condition allows one or more coroutines to wait until notified.
Like a standard `threading.Condition`, but does not need an underlying lock
that is acquired and released.
With a `Condition`, coroutines can wait to be notified by other coroutines:
..... | class Condition(_TimeoutGarbageCollector):
"""A condition allows one or more coroutines to wait until notified.
Like a standard `threading.Condition`, but does not need an underlying lock
that is acquired and released.
With a `Condition`, coroutines can wait to be notified by other coroutines:
..... | waiter = Future() # type: Future[bool]
self._waiters.append(waiter)
if timeout:
def on_timeout() -> None:
if not waiter.done():
future_set_result_unless_cancelled(waiter, False)
self._garbage_collect()
io_loop = ioloo... | """Wait for `.notify`.
Returns a `.Future` that resolves ``True`` if the condition is notified,
or ``False`` after a timeout.
"""
waiter = Future() # type: Future[bool]
self._waiters.append(waiter)
if timeout:
def on_timeout() -> None:
... | 31 | 789 | 165 | 954 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,807 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locks.py | 231,234 | 158,258 | wait | Event | 239,258 | 234,258 | class Event(object):
"""An event blocks coroutines until its internal flag is set to True.
Similar to `threading.Event`.
A coroutine can wait for an event to be set. Once it is set, calls to
``yield event.wait()`` will not block unless the event has been cleared:
.. testcode::
import asy... | class Event(object):
"""An event blocks coroutines until its internal flag is set to True.
Similar to `threading.Event`.
A coroutine can wait for an event to be set. Once it is set, calls to
``yield event.wait()`` will not block unless the event has been cleared:
.. testcode::
import asy... | fut = Future() # type: Future[None]
if self._value:
fut.set_result(None)
return fut
self._waiters.add(fut)
fut.add_done_callback(lambda fut: self._waiters.remove(fut))
if timeout is None:
return fut
else:
timeout_fut = gen.... | """Block until the internal flag is true.
Returns an awaitable, which raises `tornado.util.TimeoutError` after a
timeout.
"""
fut = Future() # type: Future[None]
if self._value:
fut.set_result(None)
return fut
self._waiters.add(fut)
... | 65 | 616 | 212 | 828 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,808 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locks.py | 530,533 | 487,573 | acquire | Lock | 538,540 | 533,540 | class Lock(object):
"""A lock for coroutines.
A Lock begins unlocked, and `acquire` locks it immediately. While it is
locked, a coroutine that yields `acquire` waits until another coroutine
calls `release`.
Releasing an unlocked lock raises `RuntimeError`.
A Lock can be used as an async conte... | class Lock(object):
"""A lock for coroutines.
A Lock begins unlocked, and `acquire` locks it immediately. While it is
locked, a coroutine that yields `acquire` waits until another coroutine
calls `release`.
Releasing an unlocked lock raises `RuntimeError`.
A Lock can be used as an async conte... | return self._block.acquire(timeout)
| """Attempt to lock. Returns an awaitable.
Returns an awaitable, which raises `tornado.util.TimeoutError` after a
timeout.
"""
return self._block.acquire(timeout)
| 2 | 707 | 15 | 722 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,809 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locks.py | 416,419 | 282,467 | acquire | Semaphore | 424,444 | 419,444 | class Semaphore(_TimeoutGarbageCollector):
"""A lock that can be acquired a fixed number of times before blocking.
A Semaphore manages a counter representing the number of `.release` calls
minus the number of `.acquire` calls, plus an initial value. The `.acquire`
method blocks if necessary until it ca... | class Semaphore(_TimeoutGarbageCollector):
"""A lock that can be acquired a fixed number of times before blocking.
A Semaphore manages a counter representing the number of `.release` calls
minus the number of `.acquire` calls, plus an initial value. The `.acquire`
method blocks if necessary until it ca... | waiter = Future() # type: Future[_ReleasingContextManager]
if self._value > 0:
self._value -= 1
waiter.set_result(_ReleasingContextManager(self))
else:
self._waiters.append(waiter)
if timeout:
def on_timeout() -> None:
... | """Decrement the counter. Returns an awaitable.
Block if the counter is zero and wait for a `.release`. The awaitable
raises `.TimeoutError` after the deadline.
"""
waiter = Future() # type: Future[_ReleasingContextManager]
if self._value > 0:
self._value -=... | 41 | 1,456 | 215 | 1,671 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,810 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/locks.py | 45,46 | 31,53 | _garbage_collect | _TimeoutGarbageCollector | 46,53 | 46,53 | class _TimeoutGarbageCollector(object):
"""Base class for objects that periodically clean up timed-out waiters.
Avoids memory leak in a common pattern like:
while True:
yield condition.wait(short_timeout)
print('looping....')
"""
def __init__(self) -> None:
sel... | class _TimeoutGarbageCollector(object):
"""Base class for objects that periodically clean up timed-out waiters.
Avoids memory leak in a common pattern like:
while True:
yield condition.wait(short_timeout)
print('looping....')
"""
def __init__(self) -> None:
sel... | # Occasionally clear timed-out waiters.
self._timeouts += 1
if self._timeouts > 100:
self._timeouts = 0
self._waiters = collections.deque(w for w in self._waiters if not w.done())
| # Occasionally clear timed-out waiters.
self._timeouts += 1
if self._timeouts > 100:
self._timeouts = 0
self._waiters = collections.deque(w for w in self._waiters if not w.done())
| 25 | 142 | 77 | 219 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,812 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/log.py | 168,169 | 81,215 | format | LogFormatter | 169,215 | 169,215 | class LogFormatter(logging.Formatter):
"""Log formatter used in Tornado.
Key features of this formatter are:
* Color support when logging to a terminal that supports it.
* Timestamps on every log line.
* Robust against str/bytes encoding problems.
This formatter is enabled automatically by
... | class LogFormatter(logging.Formatter):
"""Log formatter used in Tornado.
Key features of this formatter are:
* Color support when logging to a terminal that supports it.
* Timestamps on every log line.
* Robust against str/bytes encoding problems.
This formatter is enabled automatically by
... | try:
message = record.getMessage()
assert isinstance(message, basestring_type) # guaranteed by logging
# Encoding notes: The logging module prefers to work with character
# strings, but only enforces that log messages are instances of
# basestring. ... | try:
message = record.getMessage()
assert isinstance(message, basestring_type) # guaranteed by logging
# Encoding notes: The logging module prefers to work with character
# strings, but only enforces that log messages are instances of
# basestring. ... | 275 | 1,016 | 641 | 1,657 | #
# Copyright 2012 Facebook
#
# 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, s... | #
# Copyright 2012 Facebook
#
# 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, s... |
26,815 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/options.py | 567,568 | 531,682 | parse | _Option | 568,593 | 568,593 | class _Option(object):
# This class could almost be made generic, but the way the types
# interact with the multiple argument makes this tricky. (default
# and the callback use List[T], but type is still Type[T]).
UNSET = object()
def __init__(
self,
name: str,
default: Any ... | class _Option(object):
# This class could almost be made generic, but the way the types
# interact with the multiple argument makes this tricky. (default
# and the callback use List[T], but type is still Type[T]).
UNSET = object()
def __init__(
self,
name: str,
default: Any ... | _parse = {
datetime.datetime: self._parse_datetime,
datetime.timedelta: self._parse_timedelta,
bool: self._parse_bool,
basestring_type: self._parse_string,
}.get(
self.type, self.type
) # type: Callable[[str], Any]
if self.mult... | _parse = {
datetime.datetime: self._parse_datetime,
datetime.timedelta: self._parse_timedelta,
bool: self._parse_bool,
basestring_type: self._parse_string,
}.get(
self.type, self.type
) # type: Callable[[str], Any]
if self.mult... | 75 | 1,341 | 292 | 1,633 | #
# Copyright 2009 Facebook
#
# 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, s... | #
# Copyright 2009 Facebook
#
# 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, s... |
26,817 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/platform/asyncio.py | 709,712 | 661,719 | add_writer | AddThreadSelectorEventLoop | 712,714 | 712,714 | class AddThreadSelectorEventLoop(asyncio.AbstractEventLoop):
"""Wrap an event loop to add implementations of the ``add_reader`` method family.
Instances of this class start a second thread to run a selector.
This thread is completely hidden from the user; all callbacks are
run on the wrapped event loop... | class AddThreadSelectorEventLoop(asyncio.AbstractEventLoop):
"""Wrap an event loop to add implementations of the ``add_reader`` method family.
Instances of this class start a second thread to run a selector.
This thread is completely hidden from the user; all callbacks are
run on the wrapped event loop... | return self._selector.add_writer(fd, callback, *args)
| return self._selector.add_writer(fd, callback, *args)
| 4 | 596 | 21 | 617 | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... |
26,818 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/platform/asyncio.py | 428,429 | 392,438 | get_event_loop | AnyThreadEventLoopPolicy | 429,438 | 429,438 | class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
"""Event loop policy that allows loop creation on any thread.
The default `asyncio` event loop policy only automatically creates
event loops in the main threads. Other threads must create event
loops explicitly or `asyncio.get_event_loop` (an... | class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
"""Event loop policy that allows loop creation on any thread.
The default `asyncio` event loop policy only automatically creates
event loops in the main threads. Other threads must create event
loops explicitly or `asyncio.get_event_loop` (an... | try:
return super().get_event_loop()
except RuntimeError:
# "There is no current event loop in thread %r"
loop = self.new_event_loop()
self.set_event_loop(loop)
return loop
| try:
return super().get_event_loop()
except RuntimeError:
# "There is no current event loop in thread %r"
loop = self.new_event_loop()
self.set_event_loop(loop)
return loop
| 21 | 400 | 75 | 475 | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... |
26,819 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/platform/asyncio.py | 322,323 | 296,356 | initialize | AsyncIOLoop | 323,336 | 323,336 | class AsyncIOLoop(BaseAsyncIOLoop):
"""``AsyncIOLoop`` is an `.IOLoop` that runs on an ``asyncio`` event loop.
This class follows the usual Tornado semantics for creating new
``IOLoops``; these loops are not necessarily related to the
``asyncio`` default event loop.
Each ``AsyncIOLoop`` creates a n... | class AsyncIOLoop(BaseAsyncIOLoop):
"""``AsyncIOLoop`` is an `.IOLoop` that runs on an ``asyncio`` event loop.
This class follows the usual Tornado semantics for creating new
``IOLoops``; these loops are not necessarily related to the
``asyncio`` default event loop.
Each ``AsyncIOLoop`` creates a n... | self.is_current = False
loop = None
if "asyncio_loop" not in kwargs:
kwargs["asyncio_loop"] = loop = asyncio.new_event_loop()
try:
super().initialize(**kwargs)
except Exception:
# If initialize() does not succeed (taking ownership of the loop),... | self.is_current = False
loop = None
if "asyncio_loop" not in kwargs:
kwargs["asyncio_loop"] = loop = asyncio.new_event_loop()
try:
super().initialize(**kwargs)
except Exception:
# If initialize() does not succeed (taking ownership of the loop),... | 44 | 502 | 127 | 629 | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... |
26,820 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/platform/asyncio.py | 290,291 | 272,296 | _make_current | AsyncIOMainLoop | 291,296 | 291,296 | class AsyncIOMainLoop(BaseAsyncIOLoop):
"""``AsyncIOMainLoop`` creates an `.IOLoop` that corresponds to the
current ``asyncio`` event loop (i.e. the one returned by
``asyncio.get_event_loop()``).
.. deprecated:: 5.0
Now used automatically when appropriate; it is no longer necessary
to re... | class AsyncIOMainLoop(BaseAsyncIOLoop):
"""``AsyncIOMainLoop`` creates an `.IOLoop` that corresponds to the
current ``asyncio`` event loop (i.e. the one returned by
``asyncio.get_event_loop()``).
.. deprecated:: 5.0
Now used automatically when appropriate; it is no longer necessary
to re... | # AsyncIOMainLoop already refers to the current asyncio loop so
# nothing to do here.
pass
| # AsyncIOMainLoop already refers to the current asyncio loop so
# nothing to do here.
pass
| 16 | 207 | 36 | 243 | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... | """Bridges between the `asyncio` module and Tornado IOLoop.
.. versionadded:: 3.2
This module integrates Tornado with the ``asyncio`` module introduced
in Python 3.4. This makes it possible to combine the two libraries on
the same event loop.
.. deprecated:: 5.0
While the code in this module is still used, it is... |
26,826 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/queues.py | 415,416 | 388,423 | _init | LifoQueue | 416,418 | 416,418 | class LifoQueue(Queue):
"""A `.Queue` that retrieves the most recently put items first.
.. testcode::
import asyncio
from tornado.queues import LifoQueue
async def main():
q = LifoQueue()
q.put(3)
q.put(2)
q.put(1)
print(awa... | class LifoQueue(Queue):
"""A `.Queue` that retrieves the most recently put items first.
.. testcode::
import asyncio
from tornado.queues import LifoQueue
async def main():
q = LifoQueue()
q.put(3)
q.put(2)
q.put(1)
print(awa... | self._queue = []
| self._queue = []
| 3 | 237 | 10 | 247 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,827 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/queues.py | 384,385 | 349,388 | _get | PriorityQueue | 385,388 | 385,388 | class PriorityQueue(Queue):
"""A `.Queue` that retrieves entries in priority order, lowest first.
Entries are typically tuples like ``(priority number, data)``.
.. testcode::
import asyncio
from tornado.queues import PriorityQueue
async def main():
q = PriorityQueue()... | class PriorityQueue(Queue):
"""A `.Queue` that retrieves entries in priority order, lowest first.
Entries are typically tuples like ``(priority number, data)``.
.. testcode::
import asyncio
from tornado.queues import PriorityQueue
async def main():
q = PriorityQueue()... | return heapq.heappop(self._queue)
| return heapq.heappop(self._queue)
| 2 | 310 | 19 | 329 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,830 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 513,514 | 510,517 | match | AnyMatches | 514,517 | 514,517 | class AnyMatches(Matcher):
"""Matches any request."""
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
FILL_FUNC_BODY | class AnyMatches(Matcher):
"""Matches any request."""
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
FILL_FUNC_BODY | return {}
| return {}
| 2 | 59 | 9 | 68 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,831 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 544,545 | 535,552 | match | DefaultHostMatches | 545,552 | 545,552 | class DefaultHostMatches(Matcher):
"""Matches requests from host that is equal to application's default_host.
Always returns no match if ``X-Real-Ip`` header is present.
"""
def __init__(self, application: Any, host_pattern: Pattern) -> None:
self.application = application
self.host_pat... | class DefaultHostMatches(Matcher):
"""Matches requests from host that is equal to application's default_host.
Always returns no match if ``X-Real-Ip`` header is present.
"""
def __init__(self, application: Any, host_pattern: Pattern) -> None:
self.application = application
self.host_pat... | # Look for default host if not behind load balancer (for debugging)
if "X-Real-Ip" not in request.headers:
if self.host_pattern.match(self.application.default_host):
return {}
return None
| # Look for default host if not behind load balancer (for debugging)
if "X-Real-Ip" not in request.headers:
if self.host_pattern.match(self.application.default_host):
return {}
return None
| 23 | 135 | 71 | 206 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,832 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 528,529 | 517,535 | match | HostMatches | 529,535 | 529,535 | class HostMatches(Matcher):
"""Matches requests from hosts specified by ``host_pattern`` regex."""
def __init__(self, host_pattern: Union[str, Pattern]) -> None:
if isinstance(host_pattern, basestring_type):
if not host_pattern.endswith("$"):
host_pattern += "$"
... | class HostMatches(Matcher):
"""Matches requests from hosts specified by ``host_pattern`` regex."""
def __init__(self, host_pattern: Union[str, Pattern]) -> None:
if isinstance(host_pattern, basestring_type):
if not host_pattern.endswith("$"):
host_pattern += "$"
... | if self.host_pattern.match(request.host_name):
return {}
return None
| if self.host_pattern.match(request.host_name):
return {}
return None
| 6 | 163 | 34 | 197 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,833 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 493,494 | 490,510 | match | Matcher | 503,505 | 494,505 | class Matcher(object):
"""Represents a matcher for request features."""
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
FILL_FUNC_BODY def reverse(self, *args: Any) -> Optional[str]:
"""Reconstructs full url from matcher instance and additional arguments."""
... | class Matcher(object):
"""Represents a matcher for request features."""
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
"""Matches current instance against the request.
:arg httputil.HTTPServerRequest request: current HTTP request
:returns: a dict of p... | raise NotImplementedError()
| """Matches current instance against the request.
:arg httputil.HTTPServerRequest request: current HTTP request
:returns: a dict of parameters to be passed to the target handler
(for example, ``handler_kwargs``, ``path_args``, ``path_kwargs``
can be passed for proper `~.w... | 2 | 235 | 12 | 247 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,834 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 608,609 | 552,649 | _find_groups | PathMatches | 614,649 | 609,649 | class PathMatches(Matcher):
"""Matches requests with paths specified by ``path_pattern`` regex."""
def __init__(self, path_pattern: Union[str, Pattern]) -> None:
if isinstance(path_pattern, basestring_type):
if not path_pattern.endswith("$"):
path_pattern += "$"
... | class PathMatches(Matcher):
"""Matches requests with paths specified by ``path_pattern`` regex."""
def __init__(self, path_pattern: Union[str, Pattern]) -> None:
if isinstance(path_pattern, basestring_type):
if not path_pattern.endswith("$"):
path_pattern += "$"
... | pattern = self.regex.pattern
if pattern.startswith("^"):
pattern = pattern[1:]
if pattern.endswith("$"):
pattern = pattern[:-1]
if self.regex.groups != pattern.count("("):
# The pattern is too complicated for our simplistic matching,
# so ... | """Returns a tuple (reverse string, group count) for a url.
For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
would return ('/%s/%s/', 2).
"""
pattern = self.regex.pattern
if pattern.startswith("^"):
pattern = pattern[1:]
if patte... | 112 | 715 | 356 | 1,071 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,835 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 218,219 | 213,229 | reverse_url | ReversibleRouter | 226,229 | 219,229 | class ReversibleRouter(Router):
"""Abstract router interface for routers that can handle named routes
and support reversing them to original urls.
"""
def reverse_url(self, name: str, *args: Any) -> Optional[str]:
FILL_FUNC_BODY | class ReversibleRouter(Router):
"""Abstract router interface for routers that can handle named routes
and support reversing them to original urls.
"""
def reverse_url(self, name: str, *args: Any) -> Optional[str]:
"""Returns url string for a given route name and arguments
or ``None`` if... | raise NotImplementedError()
| """Returns url string for a given route name and arguments
or ``None`` if no match is found.
:arg str name: route name.
:arg args: url parameters.
:returns: parametrized url string for a given route name (or ``None``).
"""
raise NotImplementedError()
| 2 | 144 | 14 | 158 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,836 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 416,417 | 404,441 | process_rule | ReversibleRuleRouter | 417,428 | 417,428 | class ReversibleRuleRouter(ReversibleRouter, RuleRouter):
"""A rule-based router that implements ``reverse_url`` method.
Each rule added to this router may have a ``name`` attribute that can be
used to reconstruct an original uri. The actual reconstruction takes place
in a rule's matcher (see `Matcher.... | class ReversibleRuleRouter(ReversibleRouter, RuleRouter):
"""A rule-based router that implements ``reverse_url`` method.
Each rule added to this router may have a ``name`` attribute that can be
used to reconstruct an original uri. The actual reconstruction takes place
in a rule's matcher (see `Matcher.... | rule = super().process_rule(rule)
if rule.name:
if rule.name in self.named_rules:
app_log.warning(
"Multiple handlers named %s; replacing previous value", rule.name
)
self.named_rules[rule.name] = rule
return rule
| rule = super().process_rule(rule)
if rule.name:
if rule.name in self.named_rules:
app_log.warning(
"Multiple handlers named %s; replacing previous value", rule.name
)
self.named_rules[rule.name] = rule
return rule
| 24 | 301 | 93 | 394 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,837 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 207,210 | 190,213 | start_request | Router | 210,213 | 210,213 | class Router(httputil.HTTPServerConnectionDelegate):
"""Abstract router interface."""
def find_handler(
self, request: httputil.HTTPServerRequest, **kwargs: Any
) -> Optional[httputil.HTTPMessageDelegate]:
"""Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDe... | class Router(httputil.HTTPServerConnectionDelegate):
"""Abstract router interface."""
def find_handler(
self, request: httputil.HTTPServerRequest, **kwargs: Any
) -> Optional[httputil.HTTPMessageDelegate]:
"""Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDe... | return _RoutingDelegate(self, server_conn, request_conn)
| return _RoutingDelegate(self, server_conn, request_conn)
| 4 | 244 | 23 | 267 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,838 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 477,478 | 441,490 | reverse | Rule | 478,480 | 478,480 | class Rule(object):
"""A routing rule."""
def __init__(
self,
matcher: "Matcher",
target: Any,
target_kwargs: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
) -> None:
"""Constructs a Rule instance.
:arg Matcher matcher: a `Matcher` ins... | class Rule(object):
"""A routing rule."""
def __init__(
self,
matcher: "Matcher",
target: Any,
target_kwargs: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
) -> None:
"""Constructs a Rule instance.
:arg Matcher matcher: a `Matcher` ins... | return self.matcher.reverse(*args)
| return self.matcher.reverse(*args)
| 2 | 496 | 16 | 512 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,839 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 376,379 | 300,404 | get_target_delegate | RuleRouter | 388,404 | 379,404 | class RuleRouter(Router):
"""Rule-based router implementation."""
def __init__(self, rules: Optional[_RuleList] = None) -> None:
"""Constructs a router from an ordered list of rules::
RuleRouter([
Rule(PathMatches("/handler"), Target),
# ... more rules
... | class RuleRouter(Router):
"""Rule-based router implementation."""
def __init__(self, rules: Optional[_RuleList] = None) -> None:
"""Constructs a router from an ordered list of rules::
RuleRouter([
Rule(PathMatches("/handler"), Target),
# ... more rules
... | if isinstance(target, Router):
return target.find_handler(request, **target_params)
elif isinstance(target, httputil.HTTPServerConnectionDelegate):
assert request.connection is not None
return target.start_request(request.server_connection, request.connection)
... | """Returns an instance of `~.httputil.HTTPMessageDelegate` for a
Rule's target. This method is called by `~.find_handler` and can be
extended to provide additional target types.
:arg target: a Rule's target.
:arg httputil.HTTPServerRequest request: current request.
:arg ... | 32 | 846 | 141 | 987 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,840 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 279,280 | 275,289 | finish | _DefaultMessageDelegate | 280,289 | 280,289 | class _DefaultMessageDelegate(httputil.HTTPMessageDelegate):
def __init__(self, connection: httputil.HTTPConnection) -> None:
self.connection = connection
def finish(self) -> None:
FILL_FUNC_BODY | class _DefaultMessageDelegate(httputil.HTTPMessageDelegate):
def __init__(self, connection: httputil.HTTPConnection) -> None:
self.connection = connection
def finish(self) -> None:
FILL_FUNC_BODY | self.connection.write_headers(
httputil.ResponseStartLine("HTTP/1.1", 404, "Not Found"),
httputil.HTTPHeaders(),
)
self.connection.finish()
# _RuleList can either contain pre-constructed Rules or a sequence of
# arguments to be passed to the Rule constructor.
| self.connection.write_headers(
httputil.ResponseStartLine("HTTP/1.1", 404, "Not Found"),
httputil.HTTPHeaders(),
)
self.connection.finish()
# _RuleList can either contain pre-constructed Rules or a sequence of
# arguments to be passed to the Rule constructor.
| 28 | 65 | 95 | 160 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,841 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/routing.py | 238,243 | 229,275 | headers_received | _RoutingDelegate | 243,262 | 243,262 | class _RoutingDelegate(httputil.HTTPMessageDelegate):
def __init__(
self, router: Router, server_conn: object, request_conn: httputil.HTTPConnection
) -> None:
self.server_conn = server_conn
self.request_conn = request_conn
self.delegate = None # type: Optional[httputil.HTTPMess... | class _RoutingDelegate(httputil.HTTPMessageDelegate):
def __init__(
self, router: Router, server_conn: object, request_conn: httputil.HTTPConnection
) -> None:
self.server_conn = server_conn
self.request_conn = request_conn
self.delegate = None # type: Optional[httputil.HTTPMess... | assert isinstance(start_line, httputil.RequestStartLine)
request = httputil.HTTPServerRequest(
connection=self.request_conn,
server_connection=self.server_conn,
start_line=start_line,
headers=headers,
)
self.delegate = self.router.find_han... | assert isinstance(start_line, httputil.RequestStartLine)
request = httputil.HTTPServerRequest(
connection=self.request_conn,
server_connection=self.server_conn,
start_line=start_line,
headers=headers,
)
self.delegate = self.router.find_han... | 35 | 310 | 202 | 512 | # Copyright 2015 The Tornado Authors
#
# 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 w... | # Copyright 2015 The Tornado Authors
#
# 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 w... |
26,842 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/simple_httpclient.py | 189,190 | 79,252 | _process_queue | SimpleAsyncHTTPClient | 190,199 | 190,199 | class SimpleAsyncHTTPClient(AsyncHTTPClient):
"""Non-blocking HTTP client with no external dependencies.
This class implements an HTTP 1.1 client on top of Tornado's IOStreams.
Some features found in the curl-based AsyncHTTPClient are not yet
supported. In particular, proxies are not supported, connec... | class SimpleAsyncHTTPClient(AsyncHTTPClient):
"""Non-blocking HTTP client with no external dependencies.
This class implements an HTTP 1.1 client on top of Tornado's IOStreams.
Some features found in the curl-based AsyncHTTPClient are not yet
supported. In particular, proxies are not supported, connec... | while self.queue and len(self.active) < self.max_clients:
key, request, callback = self.queue.popleft()
if key not in self.waiting:
continue
self._remove_timeout(key)
self.active[key] = (request, callback)
release_callback = functools.p... | while self.queue and len(self.active) < self.max_clients:
key, request, callback = self.queue.popleft()
if key not in self.waiting:
continue
self._remove_timeout(key)
self.active[key] = (request, callback)
release_callback = functools.p... | 29 | 1,759 | 121 | 1,880 | from tornado.escape import _unicode
from tornado import gen, version
from tornado.httpclient import (
HTTPResponse,
HTTPError,
AsyncHTTPClient,
main,
_RequestProxy,
HTTPRequest,
)
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tor... | from tornado.escape import _unicode
from tornado import gen, version
from tornado.httpclient import (
HTTPResponse,
HTTPError,
AsyncHTTPClient,
main,
_RequestProxy,
HTTPRequest,
)
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tor... |
26,844 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/speedups.pyi | 1,1 | 1,2 | websocket_mask | 1,2 | 1,2 | FILL_FUNC_BODY | FILL_FUNC_BODY | def websocket_mask(mask: bytes, data: bytes) -> bytes: ...
| def websocket_mask(mask: bytes, data: bytes) -> bytes: ...
| 8 | 10 | 21 | 31 | FILL_FUNC_BODY | FILL_FUNC_BODY | |
26,846 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/util.py | 372,373 | 356,423 | _getargnames | ArgReplacer | 373,387 | 373,387 | class ArgReplacer(object):
"""Replaces one value in an ``args, kwargs`` pair.
Inspects the function signature to find an argument by name
whether it is passed by position or keyword. For use in decorators
and similar wrappers.
"""
def __init__(self, func: Callable, name: str) -> None:
... | class ArgReplacer(object):
"""Replaces one value in an ``args, kwargs`` pair.
Inspects the function signature to find an argument by name
whether it is passed by position or keyword. For use in decorators
and similar wrappers.
"""
def __init__(self, func: Callable, name: str) -> None:
... | try:
return getfullargspec(func).args
except TypeError:
if hasattr(func, "func_code"):
# Cython-generated code has all the attributes needed
# by inspect.getfullargspec, but the inspect module only
# works with ordinary functions. I... | try:
return getfullargspec(func).args
except TypeError:
if hasattr(func, "func_code"):
# Cython-generated code has all the attributes needed
# by inspect.getfullargspec, but the inspect module only
# works with ordinary functions. I... | 70 | 626 | 174 | 800 | """Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.
The one public-facing part of this module is the `Configurable` cl... | """Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.
The one public-facing part of this module is the `Configurable` cl... |
26,847 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/util.py | 326,328 | 221,356 | configured_class | Configurable | 328,342 | 328,342 | class Configurable(object):
"""Base class for configurable interfaces.
A configurable interface is an (abstract) class whose constructor
acts as a factory function for one of its implementation subclasses.
The implementation subclass as well as optional keyword arguments to
its initializer can be s... | class Configurable(object):
"""Base class for configurable interfaces.
A configurable interface is an (abstract) class whose constructor
acts as a factory function for one of its implementation subclasses.
The implementation subclass as well as optional keyword arguments to
its initializer can be s... | # type: () -> Type[Configurable]
"""Returns the currently configured class."""
base = cls.configurable_base()
# Manually mangle the private name to see whether this base
# has been configured (and not another base higher in the
# hierarchy).
if base.__dict__.get("... | # type: () -> Type[Configurable]
"""Returns the currently configured class."""
base = cls.configurable_base()
# Manually mangle the private name to see whether this base
# has been configured (and not another base higher in the
# hierarchy).
if base.__dict__.get("... | 67 | 1,273 | 171 | 1,444 | """Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.
The one public-facing part of this module is the `Configurable` cl... | """Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.
The one public-facing part of this module is the `Configurable` cl... |
26,848 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/util.py | 98,99 | 85,125 | decompress | GzipDecompressor | 109,111 | 99,111 | class GzipDecompressor(object):
"""Streaming gzip decompressor.
The interface is like that of `zlib.decompressobj` (without some of the
optional arguments, but it understands gzip headers and checksums.
"""
def __init__(self) -> None:
# Magic parameter makes zlib module understand gzip hea... | class GzipDecompressor(object):
"""Streaming gzip decompressor.
The interface is like that of `zlib.decompressobj` (without some of the
optional arguments, but it understands gzip headers and checksums.
"""
def __init__(self) -> None:
# Magic parameter makes zlib module understand gzip hea... | return self.decompressobj.decompress(value, max_length)
| """Decompress a chunk, returning newly-available data.
Some data may be buffered for later processing; `flush` must
be called when there is no more input data to ensure that
all data was processed.
If ``max_length`` is given, some input data may be left over
in ``uncons... | 3 | 445 | 23 | 468 | """Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.
The one public-facing part of this module is the `Configurable` cl... | """Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.
The one public-facing part of this module is the `Configurable` cl... |
26,852 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/websocket.py | 646,647 | 613,704 | _abort | WebSocketProtocol | 648,654 | 647,654 | class WebSocketProtocol(abc.ABC):
"""Base class for WebSocket protocol versions."""
def __init__(self, handler: "_WebSocketDelegate") -> None:
self.handler = handler
self.stream = None # type: Optional[IOStream]
self.client_terminated = False
self.server_terminated = False
... | class WebSocketProtocol(abc.ABC):
"""Base class for WebSocket protocol versions."""
def __init__(self, handler: "_WebSocketDelegate") -> None:
self.handler = handler
self.stream = None # type: Optional[IOStream]
self.client_terminated = False
self.server_terminated = False
... | self.client_terminated = True
self.server_terminated = True
if self.stream is not None:
self.stream.close() # forcibly tear down the connection
self.close() # let the subclass cleanup
| """Instantly aborts the WebSocket connection by closing the socket"""
self.client_terminated = True
self.server_terminated = True
if self.stream is not None:
self.stream.close() # forcibly tear down the connection
self.close() # let the subclass cleanup
| 24 | 814 | 68 | 882 | """Implementation of the WebSocket protocol.
`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server. WebSockets are supported in the
current versions of all major browsers.
This module implements the final version of the WebSocket protocol as
defined i... | """Implementation of the WebSocket protocol.
`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server. WebSockets are supported in the
current versions of all major browsers.
This module implements the final version of the WebSocket protocol as
defined i... |
26,854 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/websocket.py | 745,746 | 704,752 | compress | _PerMessageDeflateCompressor | 746,752 | 746,752 | class _PerMessageDeflateCompressor(object):
def __init__(
self,
persistent: bool,
max_wbits: Optional[int],
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
if max_wbits is None:
max_wbits = zlib.MAX_WBITS
# There is no symbolic constan... | class _PerMessageDeflateCompressor(object):
def __init__(
self,
persistent: bool,
max_wbits: Optional[int],
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
if max_wbits is None:
max_wbits = zlib.MAX_WBITS
# There is no symbolic constan... | compressor = self._compressor or self._create_compressor()
data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)
assert data.endswith(b"\x00\x00\xff\xff")
return data[:-4]
| compressor = self._compressor or self._create_compressor()
data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)
assert data.endswith(b"\x00\x00\xff\xff")
return data[:-4]
| 14 | 448 | 91 | 539 | """Implementation of the WebSocket protocol.
`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server. WebSockets are supported in the
current versions of all major browsers.
This module implements the final version of the WebSocket protocol as
defined i... | """Implementation of the WebSocket protocol.
`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server. WebSockets are supported in the
current versions of all major browsers.
This module implements the final version of the WebSocket protocol as
defined i... |
26,855 | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado | /home/hieuvd/dung_repo/raw/stars_01/tornadoweb_tornado/tornado/tornado/websocket.py | 777,778 | 752,790 | _create_decompressor | _PerMessageDeflateDecompressor | 778,780 | 778,780 | class _PerMessageDeflateDecompressor(object):
def __init__(
self,
persistent: bool,
max_wbits: Optional[int],
max_message_size: int,
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
self._max_message_size = max_message_size
if max_wbits is ... | class _PerMessageDeflateDecompressor(object):
def __init__(
self,
persistent: bool,
max_wbits: Optional[int],
max_message_size: int,
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
self._max_message_size = max_message_size
if max_wbits is ... | return zlib.decompressobj(-self._max_wbits)
| return zlib.decompressobj(-self._max_wbits)
| 2 | 396 | 21 | 417 | """Implementation of the WebSocket protocol.
`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server. WebSockets are supported in the
current versions of all major browsers.
This module implements the final version of the WebSocket protocol as
defined i... | """Implementation of the WebSocket protocol.
`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server. WebSockets are supported in the
current versions of all major browsers.
This module implements the final version of the WebSocket protocol as
defined i... |
26,917 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/models/experimental.py | 90,91 | 1,129 | attempt_load | 92,129 | 91,129 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... | from models.yolo import Detect, Model
model = Ensemble()
for w in weights if isinstance(weights, list) else [weights]:
ckpt = torch.load(attempt_download(w), map_location="cpu") # load
ckpt = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
# Model compatibility... | """Loads an ensemble or single model weights, supports device placement and model fusion."""
from models.yolo import Detect, Model
model = Ensemble()
for w in weights if isinstance(weights, list) else [weights]:
ckpt = torch.load(attempt_download(w), map_location="cpu") # load
ckpt = (... | 184 | 1,199 | 636 | 1,835 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... | |
26,918 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/models/experimental.py | 79,80 | 73,90 | forward | Ensemble | 83,90 | 80,90 | class Ensemble(nn.ModuleList):
# Ensemble of models
def __init__(self):
"""Initializes an ensemble of models to combine their outputs."""
super().__init__()
def forward(self, x, augment=False, profile=False, visualize=False):
FILL_FUNC_BODY | class Ensemble(nn.ModuleList):
# Ensemble of models
def __init__(self):
"""Initializes an ensemble of models to combine their outputs."""
super().__init__()
def forward(self, x, augment=False, profile=False, visualize=False):
"""Applies ensemble of models on input `x`, with options ... | y = [module(x, augment, profile, visualize)[0] for module in self]
# y = torch.stack(y).max(0)[0] # max ensemble
# y = torch.stack(y).mean(0) # mean ensemble
y = torch.cat(y, 1) # nms ensemble
return y, None # inference, train output
| """Applies ensemble of models on input `x`, with options for augmentation, profiling, and visualization,
returning inference outputs.
"""
y = [module(x, augment, profile, visualize)[0] for module in self]
# y = torch.stack(y).max(0)[0] # max ensemble
# y = torch.stack(y)... | 38 | 116 | 105 | 221 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... |
26,919 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/models/experimental.py | 68,69 | 44,73 | forward | MixConv2d | 70,73 | 69,73 | class MixConv2d(nn.Module):
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
"""Initializes MixConv2d with mixed depth-wise convolution layers; details at
https://arxiv.org/abs/1907.09... | class MixConv2d(nn.Module):
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
"""Initializes MixConv2d with mixed depth-wise convolution layers; details at
https://arxiv.org/abs/1907.09... | return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
| """Applies a series of convolutions, batch normalization, and SiLU activation to input tensor `x`."""
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
| 7 | 507 | 35 | 542 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... |
26,920 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/models/experimental.py | 27,28 | 13,44 | forward | Sum | 33,44 | 28,44 | class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=False): # n: number of inputs
"""
Initializes a module to compute weighted/unweighted sum of n inputs, with optional learning weights.
https://arxiv.org/abs/1911.09070... | class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=False): # n: number of inputs
"""
Initializes a module to compute weighted/unweighted sum of n inputs, with optional learning weights.
https://arxiv.org/abs/1911.09070... | y = x[0] # no weight
if self.weight:
w = torch.sigmoid(self.w) * 2
for i in self.iter:
y = y + x[i + 1] * w[i]
else:
for i in self.iter:
y = y + x[i + 1]
return y
| """
Performs forward pass, blending `x` elements with optional learnable weights.
See https://arxiv.org/abs/1911.09070 for more.
"""
y = x[0] # no weight
if self.weight:
w = torch.sigmoid(self.w) * 2
for i in self.iter:
y = y + x[... | 40 | 264 | 105 | 369 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Experimental modules."""
import math
import numpy as np
import torch
import torch.nn as nn
from utils.downloads import attempt_download
class Sum(nn.Module):
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
def __init__(self, n, weight=Fals... |
26,921 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 94,95 | 80,101 | forward | AconC | 97,101 | 95,101 | class AconC(nn.Module):
r"""ACON activation (activate or not)
AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
"""
def __init__(self, c1):
"""Initialize... | class AconC(nn.Module):
r"""ACON activation (activate or not)
AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
"""
def __init__(self, c1):
"""Initialize... | dpx = (self.p1 - self.p2) * x
return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
| """Applies a parametric activation function to tensor x; see https://arxiv.org/pdf/2009.04759.pdf for
details."""
dpx = (self.p1 - self.p2) * x
return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
| 17 | 327 | 51 | 378 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,922 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 43,45 | 42,61 | forward | F | 48,51 | 45,51 | class F(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
FILL_FUNC_BODY @staticmethod
def backward(ctx, grad_output):
"""Computes gradient of the Mish activation function for backpropagation, returning the derivative with
respect to the input.
... | class F(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
"""Applies the Mish activation function in a memory-efficient manner, useful for enhancing model
performance.
"""
FILL_FUNC_BODY @staticmethod
def backward(ctx, grad_output):
... | ctx.save_for_backward(x)
return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
| """Applies the Mish activation function in a memory-efficient manner, useful for enhancing model
performance.
"""
ctx.save_for_backward(x)
return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
| 9 | 184 | 53 | 237 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,923 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 75,76 | 66,80 | forward | FReLU | 77,80 | 76,80 | class FReLU(nn.Module):
# FReLU activation https://arxiv.org/abs/2007.11824
def __init__(self, c1, k=3): # ch_in, kernel
"""Initializes FReLU with specified channel size and kernel, implementing activation from
https://arxiv.org/abs/2007.11824."""
super().__init__()
self.conv = ... | class FReLU(nn.Module):
# FReLU activation https://arxiv.org/abs/2007.11824
def __init__(self, c1, k=3): # ch_in, kernel
"""Initializes FReLU with specified channel size and kernel, implementing activation from
https://arxiv.org/abs/2007.11824."""
super().__init__()
self.conv = ... | return torch.max(x, self.bn(self.conv(x)))
| """Performs FReLU activation on input, returning the max of input and its 2D convolution."""
return torch.max(x, self.bn(self.conv(x)))
| 3 | 210 | 25 | 235 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,924 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 20,22 | 18,28 | forward | Hardswish | 25,28 | 22,28 | class Hardswish(nn.Module):
# Hard-SiLU activation
@staticmethod
def forward(x):
FILL_FUNC_BODY | class Hardswish(nn.Module):
# Hard-SiLU activation
@staticmethod
def forward(x):
"""Applies Hardswish activation, suitable for TorchScript, CoreML, ONNX, modifying input `x` as per Hard-SiLU
definition.
"""
FILL_FUNC_BODY | return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
| """Applies Hardswish activation, suitable for TorchScript, CoreML, ONNX, modifying input `x` as per Hard-SiLU
definition.
"""
return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
| 16 | 84 | 48 | 132 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,925 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 51,53 | 40,66 | backward | MemoryEfficientMish | 56,61 | 53,61 | class MemoryEfficientMish(nn.Module):
# Mish activation memory-efficient
class F(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
"""Applies the Mish activation function in a memory-efficient manner, useful for enhancing model
performance.
"""
... | class MemoryEfficientMish(nn.Module):
# Mish activation memory-efficient
class F(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
"""Applies the Mish activation function in a memory-efficient manner, useful for enhancing model
performance.
"""
... | x = ctx.saved_tensors[0]
sx = torch.sigmoid(x)
fx = F.softplus(x).tanh()
return grad_output * (fx + x * sx * (1 - fx * fx))
| """Computes gradient of the Mish activation function for backpropagation, returning the derivative with
respect to the input.
"""
x = ctx.saved_tensors[0]
sx = torch.sigmoid(x)
fx = F.softplus(x).tanh()
return grad_output * (fx + x * sx... | 23 | 228 | 74 | 302 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,926 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 120,121 | 101,128 | forward | MetaAconC | 122,128 | 121,128 | class MetaAconC(nn.Module):
r"""ACON activation (activate or not)
MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
"""
def __init__(self, c1, k=1, s=... | class MetaAconC(nn.Module):
r"""ACON activation (activate or not)
MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
"""
def __init__(self, c1, k=1, s=... | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
# batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
# beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN lay... | """Applies a forward pass transforming input `x` using parametric operations and returns the modified tensor."""
y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
# batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
# beta = torch.sigmoid(self.bn2(... | 42 | 419 | 185 | 604 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,927 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 30,32 | 28,40 | forward | Mish | 37,40 | 32,40 | class Mish(nn.Module):
# Mish activation https://github.com/digantamisra98/Mish
@staticmethod
def forward(x):
FILL_FUNC_BODY | class Mish(nn.Module):
# Mish activation https://github.com/digantamisra98/Mish
@staticmethod
def forward(x):
"""
Applies the Mish activation function, enhancing model performance and convergence.
Reference: https://github.com/digantamisra98/Mish
"""
FILL_FUNC_BODY | return x * F.softplus(x).tanh()
| """
Applies the Mish activation function, enhancing model performance and convergence.
Reference: https://github.com/digantamisra98/Mish
"""
return x * F.softplus(x).tanh()
| 4 | 97 | 20 | 117 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,928 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/activations.py | 11,13 | 9,18 | forward | SiLU | 15,18 | 13,18 | class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
FILL_FUNC_BODY | class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detailed in https://arxiv.org/pdf/1606.08415.pdf, on input tensor
`x`."""
FILL_FUNC_BODY | return x * torch.sigmoid(x)
| """Applies the SiLU activation function, as detailed in https://arxiv.org/pdf/1606.08415.pdf, on input tensor
`x`."""
return x * torch.sigmoid(x)
| 4 | 108 | 19 | 127 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
FILL_FUNC_BODYclass Hardswish(nn.Module):
# Hard-SiLU... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Activation functions."""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
@staticmethod
def forward(x):
"""Applies the SiLU activation function, as detai... |
26,930 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/autobatch.py | 19,20 | 1,73 | autobatch | 23,73 | 20,73 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Auto-batch utils."""
from copy import deepcopy
import numpy as np
import torch
from utils.general import LOGGER, colorstr
from utils.torch_utils import profile
def check_train_batch_size(model, imgsz=640, amp=True):
"""Checks and computes the optimal training bat... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Auto-batch utils."""
from copy import deepcopy
import numpy as np
import torch
from utils.general import LOGGER, colorstr
from utils.torch_utils import profile
def check_train_batch_size(model, imgsz=640, amp=True):
"""Checks and computes the optimal training bat... | # Usage:
# import torch
# from utils.autobatch import autobatch
# model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
# print(autobatch(model))
# Check device
prefix = colorstr("AutoBatch: ")
LOGGER.info(f"{prefix}Computing optimal batch size for --i... | """Estimates optimal YOLOv3 batch size using available CUDA memory; imgsz:int=640, fraction:float=0.8,
batch_size:int=16.
"""
# Usage:
# import torch
# from utils.autobatch import autobatch
# model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
# print... | 303 | 259 | 933 | 1,192 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Auto-batch utils."""
from copy import deepcopy
import numpy as np
import torch
from utils.general import LOGGER, colorstr
from utils.torch_utils import profile
def check_train_batch_size(model, imgsz=640, amp=True):
"""Checks and computes the optimal training bat... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Auto-batch utils."""
from copy import deepcopy
import numpy as np
import torch
from utils.general import LOGGER, colorstr
from utils.torch_utils import profile
def check_train_batch_size(model, imgsz=640, amp=True):
"""Checks and computes the optimal training bat... | |
26,931 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/callbacks.py | 35,36 | 7,74 | register_action | Callbacks | 44,48 | 36,48 | class Callbacks:
"""" Handles all registered callbacks for YOLOv3 Hooks."""
def __init__(self):
"""Initializes a Callbacks object to manage YOLOv3 training hooks with various event triggers."""
self._callbacks = {
"on_pretrain_routine_start": [],
"on_pretrain_routine_end... | class Callbacks:
"""" Handles all registered callbacks for YOLOv3 Hooks."""
def __init__(self):
"""Initializes a Callbacks object to manage YOLOv3 training hooks with various event triggers."""
self._callbacks = {
"on_pretrain_routine_start": [],
"on_pretrain_routine_end... | assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
assert callable(callback), f"callback '{callback}' is not callable"
self._callbacks[hook].append({"name": name, "callback": callback})
| """
Register a new action to a callback hook.
Args:
hook: The callback hook name to register the action to
name: The name of the action for later reference
callback: The callback to fire
"""
assert hook in self._callbacks, f"hook '{hook}' not ... | 22 | 669 | 74 | 743 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Callback utils."""
import threading
class Callbacks:
"""" Handles all registered callbacks for YOLOv3 Hooks."""
def __init__(self):
"""Initializes a Callbacks object to manage YOLOv3 training hooks with various event triggers."""
self._callback... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Callback utils."""
import threading
class Callbacks:
"""" Handles all registered callbacks for YOLOv3 Hooks."""
def __init__(self):
"""Initializes a Callbacks object to manage YOLOv3 training hooks with various event triggers."""
self._callback... |
26,932 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/downloads.py | 36,37 | 1,129 | curl_download | 38,56 | 37,56 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Download utils."""
import logging
import subprocess
import urllib
from pathlib import Path
import requests
import torch
def is_url(url, check=True):
"""Determines if a string is a valid URL and optionally checks its existence online."""
try:
url = str(... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Download utils."""
import logging
import subprocess
import urllib
from pathlib import Path
import requests
import torch
def is_url(url, check=True):
"""Determines if a string is a valid URL and optionally checks its existence online."""
try:
url = str(... | silent_option = "sS" if silent else "" # silent
proc = subprocess.run(
[
"curl",
"-#",
f"-{silent_option}L",
url,
"--output",
filename,
"--retry",
"9",
"-C",
"-",
]
)
... | """Download a file from a url to a filename using curl."""
silent_option = "sS" if silent else "" # silent
proc = subprocess.run(
[
"curl",
"-#",
f"-{silent_option}L",
url,
"--output",
filename,
"--retry",
... | 29 | 1,504 | 121 | 1,625 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Download utils."""
import logging
import subprocess
import urllib
from pathlib import Path
import requests
import torch
def is_url(url, check=True):
"""Determines if a string is a valid URL and optionally checks its existence online."""
try:
url = str(... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Download utils."""
import logging
import subprocess
import urllib
from pathlib import Path
import requests
import torch
def is_url(url, check=True):
"""Determines if a string is a valid URL and optionally checks its existence online."""
try:
url = str(... | |
26,934 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/loggers/clearml/clearml_utils.py | 142,143 | 63,175 | log_image_with_boxes | ClearmlLogger | 152,175 | 143,175 | class ClearmlLogger:
"""
Log training runs, datasets, models, and predictions to ClearML.
This logger sends information to ClearML at app.clear.ml or to your own hosted server. By default, this information
includes hyperparameters, system configuration and metrics, model metrics, code information and b... | class ClearmlLogger:
"""
Log training runs, datasets, models, and predictions to ClearML.
This logger sends information to ClearML at app.clear.ml or to your own hosted server. By default, this information
includes hyperparameters, system configuration and metrics, model metrics, code information and b... | if (
len(self.current_epoch_logged_images) < self.max_imgs_to_log_per_epoch
and self.current_epoch >= 0
and (self.current_epoch % self.bbox_interval == 0 and image_path not in self.current_epoch_logged_images)
):
im = np.ascontiguousarray(np.moveaxis(image... | """
Draw the bounding boxes on a single image and report the result as a ClearML debug sample.
arguments:
image_path (PosixPath) the path the original image file
boxes (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
class_na... | 79 | 1,126 | 426 | 1,552 | """Main Logger class for ClearML experiment tracking."""
import glob
import re
from pathlib import Path
import numpy as np
import yaml
from ultralytics.utils.plotting import Annotator, colors
try:
import clearml
from clearml import Dataset, Task
assert hasattr(clearml, "__version__") # verify package i... | """Main Logger class for ClearML experiment tracking."""
import glob
import re
from pathlib import Path
import numpy as np
import yaml
from ultralytics.utils.plotting import Annotator, colors
try:
import clearml
from clearml import Dataset, Task
assert hasattr(clearml, "__version__") # verify package i... |
26,935 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/loggers/comet/comet_utils.py | 67,68 | 1,150 | set_opt_parameters | 75,98 | 68,98 | import logging
import os
from urllib.parse import urlparse
try:
import comet_ml
except ImportError:
comet_ml = None
import yaml
logger = logging.getLogger(__name__)
COMET_PREFIX = "comet://"
COMET_MODEL_NAME = os.getenv("COMET_MODEL_NAME", "yolov5")
COMET_DEFAULT_CHECKPOINT_FILENAME = os.getenv("COMET_DEFAU... | import logging
import os
from urllib.parse import urlparse
try:
import comet_ml
except ImportError:
comet_ml = None
import yaml
logger = logging.getLogger(__name__)
COMET_PREFIX = "comet://"
COMET_MODEL_NAME = os.getenv("COMET_MODEL_NAME", "yolov5")
COMET_DEFAULT_CHECKPOINT_FILENAME = os.getenv("COMET_DEFAU... | asset_list = experiment.get_asset_list()
resume_string = opt.resume
for asset in asset_list:
if asset["fileName"] == "opt.yaml":
asset_id = asset["assetId"]
asset_binary = experiment.get_asset(asset_id, return_type="binary", stream=False)
opt_dict = yaml.safe_loa... | """
Update the opts Namespace with parameters from Comet's ExistingExperiment when resuming a run.
Args:
opt (argparse.Namespace): Namespace of command line options
experiment (comet_ml.APIExperiment): Comet API Experiment object
"""
asset_list = experiment.get_asset_list()
resu... | 68 | 1,212 | 294 | 1,506 | import logging
import os
from urllib.parse import urlparse
try:
import comet_ml
except ImportError:
comet_ml = None
import yaml
logger = logging.getLogger(__name__)
COMET_PREFIX = "comet://"
COMET_MODEL_NAME = os.getenv("COMET_MODEL_NAME", "yolov5")
COMET_DEFAULT_CHECKPOINT_FILENAME = os.getenv("COMET_DEFAU... | import logging
import os
from urllib.parse import urlparse
try:
import comet_ml
except ImportError:
comet_ml = None
import yaml
logger = logging.getLogger(__name__)
COMET_PREFIX = "comet://"
COMET_MODEL_NAME = os.getenv("COMET_MODEL_NAME", "yolov5")
COMET_DEFAULT_CHECKPOINT_FILENAME = os.getenv("COMET_DEFAU... | |
26,937 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/loss.py | 24,25 | 16,37 | forward | BCEBlurWithLogitsLoss | 28,37 | 25,37 | class BCEBlurWithLogitsLoss(nn.Module):
# BCEwithLogitLoss() with reduced missing label effects.
def __init__(self, alpha=0.05):
"""Initializes BCEBlurWithLogitsLoss with alpha to reduce missing label effects; default alpha is 0.05."""
super().__init__()
self.loss_fcn = nn.BCEWithLogitsL... | class BCEBlurWithLogitsLoss(nn.Module):
# BCEwithLogitLoss() with reduced missing label effects.
def __init__(self, alpha=0.05):
"""Initializes BCEBlurWithLogitsLoss with alpha to reduce missing label effects; default alpha is 0.05."""
super().__init__()
self.loss_fcn = nn.BCEWithLogitsL... | loss = self.loss_fcn(pred, true)
pred = torch.sigmoid(pred) # prob from logits
dx = pred - true # reduce only missing label effects
# dx = (pred - true).abs() # reduce missing label and false label effects
alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
lo... | """Calculates modified BCEWithLogitsLoss factoring in missing labels, taking `pred` logits and `true` labels as
inputs.
"""
loss = self.loss_fcn(pred, true)
pred = torch.sigmoid(pred) # prob from logits
dx = pred - true # reduce only missing label effects
# dx =... | 52 | 195 | 124 | 319 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Loss functions."""
import torch
import torch.nn as nn
from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
"""Applies label smoothing to BCE... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Loss functions."""
import torch
import torch.nn as nn
from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
"""Applies label smoothing to BCE... |
26,939 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/loss.py | 50,51 | 37,73 | forward | FocalLoss | 54,73 | 51,73 | class FocalLoss(nn.Module):
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
"""Initializes FocalLoss with specified loss function, gamma, and alpha for enhanced training on imbalanced
... | class FocalLoss(nn.Module):
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
"""Initializes FocalLoss with specified loss function, gamma, and alpha for enhanced training on imbalanced
... | loss = self.loss_fcn(pred, true)
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
# TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
pred_prob = torch.... | """Computes the focal loss between `pred` and `true` using specific alpha and gamma, not applying the modulating
factor.
"""
loss = self.loss_fcn(pred, true)
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stab... | 90 | 255 | 284 | 539 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Loss functions."""
import torch
import torch.nn as nn
from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
"""Applies label smoothing to BCE... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Loss functions."""
import torch
import torch.nn as nn
from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
"""Applies label smoothing to BCE... |
26,940 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/loss.py | 86,87 | 73,105 | forward | QFocalLoss | 90,105 | 87,105 | class QFocalLoss(nn.Module):
# Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
"""Initializes QFocalLoss with specified loss function, gamma, and alpha for element-wise focal loss
... | class QFocalLoss(nn.Module):
# Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
"""Initializes QFocalLoss with specified loss function, gamma, and alpha for element-wise focal loss
... | loss = self.loss_fcn(pred, true)
pred_prob = torch.sigmoid(pred) # prob from logits
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
modulating_factor = torch.abs(true - pred_prob) ** self.gamma
loss *= alpha_factor * modulating_factor
if self.reduction... | """Computes focal loss between predictions and true labels using configured loss function, `gamma`, and
`alpha`.
"""
loss = self.loss_fcn(pred, true)
pred_prob = torch.sigmoid(pred) # prob from logits
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
... | 53 | 254 | 164 | 418 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Loss functions."""
import torch
import torch.nn as nn
from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
"""Applies label smoothing to BCE... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Loss functions."""
import torch
import torch.nn as nn
from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
"""Applies label smoothing to BCE... |
26,941 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/segment/augmentations.py | 24,27 | 1,98 | random_perspective | 27,98 | 27,98 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Image augmentation functions."""
import math
import random
import cv2
import numpy as np
from ..augmentations import box_candidates
from ..general import resample_segments, segment2box
def mixup(im, labels, segments, im2, labels2, segments2):
"""Applies MixUp aug... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Image augmentation functions."""
import math
import random
import cv2
import numpy as np
from ..augmentations import box_candidates
from ..general import resample_segments, segment2box
def mixup(im, labels, segments, im2, labels2, segments2):
"""Applies MixUp aug... | # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -im.shape[1] / 2 # x translation... | # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -im.shape[1] / 2 # x translation... | 371 | 318 | 1,227 | 1,545 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Image augmentation functions."""
import math
import random
import cv2
import numpy as np
from ..augmentations import box_candidates
from ..general import resample_segments, segment2box
def mixup(im, labels, segments, im2, labels2, segments2):
"""Applies MixUp aug... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Image augmentation functions."""
import math
import random
import cv2
import numpy as np
from ..augmentations import box_candidates
from ..general import resample_segments, segment2box
def mixup(im, labels, segments, im2, labels2, segments2):
"""Applies MixUp aug... | |
26,943 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/segment/metrics.py | 92,94 | 56,152 | mr | Metric | 100,102 | 94,102 | class Metric:
def __init__(self) -> None:
self.p = [] # (nc, )
self.r = [] # (nc, )
self.f1 = [] # (nc, )
self.all_ap = [] # (nc, 10)
self.ap_class_index = [] # (nc, )
@property
def ap50(self):
"""
AP@0.5 of all classes.
Return:
... | class Metric:
def __init__(self) -> None:
self.p = [] # (nc, )
self.r = [] # (nc, )
self.f1 = [] # (nc, )
self.all_ap = [] # (nc, 10)
self.ap_class_index = [] # (nc, )
@property
def ap50(self):
"""
AP@0.5 of all classes.
Return:
... | return self.r.mean() if len(self.r) else 0.0
| """
Mean recall of all classes.
Return:
float.
"""
return self.r.mean() if len(self.r) else 0.0
| 6 | 806 | 24 | 830 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Model validation metrics."""
import numpy as np
from ..metrics import ap_per_class
def fitness(x):
"""Calculates model fitness as a weighted sum of 8 metrics, where `x` is an array of shape [N, 8]."""
w = [0.0, 0.0, 0.1, 0.9, 0.0, 0.0, 0.1, 0.9]
return (x[... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Model validation metrics."""
import numpy as np
from ..metrics import ap_per_class
def fitness(x):
"""Calculates model fitness as a weighted sum of 8 metrics, where `x` is an array of shape [N, 8]."""
w = [0.0, 0.0, 0.1, 0.9, 0.0, 0.0, 0.1, 0.9]
return (x[... |
26,944 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/segment/metrics.py | 159,160 | 152,185 | update | Metrics | 164,167 | 160,167 | class Metrics:
"""Metric for boxes and masks."""
def __init__(self) -> None:
self.metric_box = Metric()
self.metric_mask = Metric()
def update(self, results):
FILL_FUNC_BODY def mean_results(self):
"""Calculates and returns the sum of mean results from 'metric_box' and 'metric_m... | class Metrics:
"""Metric for boxes and masks."""
def __init__(self) -> None:
self.metric_box = Metric()
self.metric_mask = Metric()
def update(self, results):
"""
Args:
results: Dict{'boxes': Dict{}, 'masks': Dict{}}
"""
FILL_FUNC_BODY def mean_result... | self.metric_box.update(list(results["boxes"].values()))
self.metric_mask.update(list(results["masks"].values()))
| """
Args:
results: Dict{'boxes': Dict{}, 'masks': Dict{}}
"""
self.metric_box.update(list(results["boxes"].values()))
self.metric_mask.update(list(results["masks"].values()))
| 2 | 350 | 42 | 392 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Model validation metrics."""
import numpy as np
from ..metrics import ap_per_class
def fitness(x):
"""Calculates model fitness as a weighted sum of 8 metrics, where `x` is an array of shape [N, 8]."""
w = [0.0, 0.0, 0.1, 0.9, 0.0, 0.0, 0.1, 0.9]
return (x[... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""Model validation metrics."""
import numpy as np
from ..metrics import ap_per_class
def fitness(x):
"""Calculates model fitness as a weighted sum of 8 metrics, where `x` is an array of shape [N, 8]."""
w = [0.0, 0.0, 0.1, 0.9, 0.0, 0.0, 0.1, 0.9]
return (x[... |
26,947 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3 | /home/hieuvd/dung_repo/raw/stars_01/ultralytics_yolov3/yolov3/utils/torch_utils.py | 480,481 | 452,483 | update_attr | ModelEMA | 482,483 | 481,483 | class ModelEMA:
"""Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models
Keeps a moving average of everything in the model state_dict (parameters and buffers)
For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
"""
... | class ModelEMA:
"""Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models
Keeps a moving average of everything in the model state_dict (parameters and buffers)
For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
"""
... | copy_attr(self.ema, model, include, exclude)
| """Updates EMA attributes by copying from model, excluding 'process_group' and 'reducer' by default."""
copy_attr(self.ema, model, include, exclude)
| 4 | 528 | 17 | 545 | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""PyTorch utils."""
import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torc... | # YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""PyTorch utils."""
import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torc... |
26,983 | /home/hieuvd/dung_repo/raw/stars_01/vinta_awesome-python/awesome-python | /home/hieuvd/dung_repo/raw/stars_01/vinta_awesome-python/awesome-python/sort.py | 45,46 | 1,84 | main | 46,82 | 46,82 | #!/usr/bin/env python
# coding: utf-8
"""
The approach taken is explained below. I decided to do it simply.
Initially I was considering parsing the data into some sort of
structure and then generating an appropriate README. I am still
considering doing it - but for now this should work. The only issue
... | #!/usr/bin/env python
# coding: utf-8
"""
The approach taken is explained below. I decided to do it simply.
Initially I was considering parsing the data into some sort of
structure and then generating an appropriate README. I am still
considering doing it - but for now this should work. The only issue
... | # First, we load the current README into memory as an array of lines
with open('README.md', 'r') as read_me_file:
read_me = read_me_file.readlines()
# Then we cluster the lines together as blocks
# Each block represents a collection of lines that should be sorted
# This was done by assuming... | # First, we load the current README into memory as an array of lines
with open('README.md', 'r') as read_me_file:
read_me = read_me_file.readlines()
# Then we cluster the lines together as blocks
# Each block represents a collection of lines that should be sorted
# This was done by assuming... | 147 | 557 | 388 | 945 | #!/usr/bin/env python
# coding: utf-8
"""
The approach taken is explained below. I decided to do it simply.
Initially I was considering parsing the data into some sort of
structure and then generating an appropriate README. I am still
considering doing it - but for now this should work. The only issue
... | #!/usr/bin/env python
# coding: utf-8
"""
The approach taken is explained below. I decided to do it simply.
Initially I was considering parsing the data into some sort of
structure and then generating an appropriate README. I am still
considering doing it - but for now this should work. The only issue
... | |
26,988 | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url/173.py | 26,27 | 1,38 | get_real_url | 27,35 | 27,35 | # 艺气山直播:http://www.173.com/room/category?categoryId=11
import requests
class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
params = f'roomId={self.rid}'
with requests.Session() as s:
res = s.post('https://www.173.com/room/getVieoUrl', params=params... | # 艺气山直播:http://www.173.com/room/category?categoryId=11
import requests
class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
params = f'roomId={self.rid}'
with requests.Session() as s:
res = s.post('https://www.173.com/room/getVieoUrl', params=params... | try:
yqs = YQS(rid)
return yqs.get_real_url()
except Exception as e:
print('Exception:', e)
return False
| try:
yqs = YQS(rid)
return yqs.get_real_url()
except Exception as e:
print('Exception:', e)
return False
| 14 | 251 | 60 | 311 | # 艺气山直播:http://www.173.com/room/category?categoryId=11
import requests
class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
params = f'roomId={self.rid}'
with requests.Session() as s:
res = s.post('https://www.173.com/room/getVieoUrl', params=params... | # 艺气山直播:http://www.173.com/room/category?categoryId=11
import requests
class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
params = f'roomId={self.rid}'
with requests.Session() as s:
res = s.post('https://www.173.com/room/getVieoUrl', params=params... | |
26,989 | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url/173.py | 11,12 | 6,26 | get_real_url | YQS | 12,26 | 12,26 | class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
FILL_FUNC_BODY | class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
FILL_FUNC_BODY | params = f'roomId={self.rid}'
with requests.Session() as s:
res = s.post('https://www.173.com/room/getVieoUrl', params=params).json()
data = res['data']
if data:
status = data['status']
if status == 2:
return data['url']
els... | params = f'roomId={self.rid}'
with requests.Session() as s:
res = s.post('https://www.173.com/room/getVieoUrl', params=params).json()
data = res['data']
if data:
status = data['status']
if status == 2:
return data['url']
els... | 31 | 46 | 134 | 180 | # 艺气山直播:http://www.173.com/room/category?categoryId=11
import requests
class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
FILL_FUNC_BODYdef get_real_url(rid):
try:
yqs = YQS(rid)
return yqs.get_real_url()
except Exception as e:
print('Exceptio... | # 艺气山直播:http://www.173.com/room/category?categoryId=11
import requests
class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
FILL_FUNC_BODYdef get_real_url(rid):
try:
yqs = YQS(rid)
return yqs.get_real_url()
except Exception as e:
print('Exceptio... |
26,990 | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url/17live.py | 34,35 | 1,46 | get_real_url | 35,43 | 35,43 | # 获取17直播的真实流媒体地址,可能需要挂国外代理才行。
# 17直播间链接形式:https://17.live/live/276480
import requests
class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
... | # 获取17直播的真实流媒体地址,可能需要挂国外代理才行。
# 17直播间链接形式:https://17.live/live/276480
import requests
class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
... | try:
live17 = Live17(rid)
return live17.get_real_url()
except Exception as e:
print('Exception:', e)
return False
| try:
live17 = Live17(rid)
return live17.get_real_url()
except Exception as e:
print('Exception:', e)
return False
| 14 | 437 | 60 | 497 | # 获取17直播的真实流媒体地址,可能需要挂国外代理才行。
# 17直播间链接形式:https://17.live/live/276480
import requests
class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
... | # 获取17直播的真实流媒体地址,可能需要挂国外代理才行。
# 17直播间链接形式:https://17.live/live/276480
import requests
class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
... | |
26,991 | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url/17live.py | 22,23 | 7,34 | get_real_url | Live17 | 23,34 | 23,34 | class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
"""
self.rid = rid
self.BASE_URL = 'https://api-dsa.17app.co/api/v... | class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
"""
self.rid = rid
self.BASE_URL = 'https://api-dsa.17app.co/api/v... | try:
# res = requests.get(f'{self.BASE_URL}{self.rid}', proxies=self.proxies).json()
res = requests.get(f'{self.BASE_URL}{self.rid}').json()
real_url_default = res.get('rtmpUrls')[0].get('url')
real_url_modify = real_url_default.replace('global-pull-rtmp.17app.co'... | try:
# res = requests.get(f'{self.BASE_URL}{self.rid}', proxies=self.proxies).json()
res = requests.get(f'{self.BASE_URL}{self.rid}').json()
real_url_default = res.get('rtmpUrls')[0].get('url')
real_url_modify = real_url_default.replace('global-pull-rtmp.17app.co'... | 26 | 149 | 194 | 343 | # 获取17直播的真实流媒体地址,可能需要挂国外代理才行。
# 17直播间链接形式:https://17.live/live/276480
import requests
class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
... | # 获取17直播的真实流媒体地址,可能需要挂国外代理才行。
# 17直播间链接形式:https://17.live/live/276480
import requests
class Live17:
def __init__(self, rid):
"""
# 可能需要挂代理。
# self.proxies = {
# "http": "http://xxxx:1080",
# "https": "http://xxxx:1080",
# }
Args:
rid:
... |
26,992 | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url | /home/hieuvd/dung_repo/raw/stars_01/wbt5_real-url/real-url/2cq.py | 26,27 | 1,38 | get_real_url | 27,35 | 27,35 | # 棉花糖直播:https://www.2cq.com/rank
import requests
class MHT:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
with requests.Session() as s:
res = s.get(f'https://www.2cq.com/proxy/room/room/info?roomId={self.rid}&appId=1004')
res = res.json()
if res... | # 棉花糖直播:https://www.2cq.com/rank
import requests
class MHT:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
with requests.Session() as s:
res = s.get(f'https://www.2cq.com/proxy/room/room/info?roomId={self.rid}&appId=1004')
res = res.json()
if res... | try:
mht = MHT(rid)
return mht.get_real_url()
except Exception as e:
print('Exception:', e)
return False
| try:
mht = MHT(rid)
return mht.get_real_url()
except Exception as e:
print('Exception:', e)
return False
| 14 | 260 | 57 | 317 | # 棉花糖直播:https://www.2cq.com/rank
import requests
class MHT:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
with requests.Session() as s:
res = s.get(f'https://www.2cq.com/proxy/room/room/info?roomId={self.rid}&appId=1004')
res = res.json()
if res... | # 棉花糖直播:https://www.2cq.com/rank
import requests
class MHT:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
with requests.Session() as s:
res = s.get(f'https://www.2cq.com/proxy/room/room/info?roomId={self.rid}&appId=1004')
res = res.json()
if res... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.