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
23,932
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/plugins/tor_check.py
46,47
1,92
post_search
47,92
47,92
# SPDX-License-Identifier: AGPL-3.0-or-later """A plugin to check if the ip address of the request is a Tor exit-node if the user searches for ``tor-check``. It fetches the tor exit node list from https://check.torproject.org/exit-addresses and parses all the IPs into a list, then checks if the user's IP address is in...
# SPDX-License-Identifier: AGPL-3.0-or-later """A plugin to check if the ip address of the request is a Tor exit-node if the user searches for ``tor-check``. It fetches the tor exit node list from https://check.torproject.org/exit-addresses and parses all the IPs into a list, then checks if the user's IP address is in...
if search.search_query.pageno > 1: return True if search.search_query.query.lower() == "tor-check": # Request the list of tor exit nodes. try: resp = get("https://check.torproject.org/exit-addresses") node_list = re.findall(reg, resp.text) except HTTPE...
if search.search_query.pageno > 1: return True if search.search_query.query.lower() == "tor-check": # Request the list of tor exit nodes. try: resp = get("https://check.torproject.org/exit-addresses") node_list = re.findall(reg, resp.text) except HTTPE...
117
387
437
824
# SPDX-License-Identifier: AGPL-3.0-or-later """A plugin to check if the ip address of the request is a Tor exit-node if the user searches for ``tor-check``. It fetches the tor exit node list from https://check.torproject.org/exit-addresses and parses all the IPs into a list, then checks if the user's IP address is in...
# SPDX-License-Identifier: AGPL-3.0-or-later """A plugin to check if the ip address of the request is a Tor exit-node if the user searches for ``tor-check``. It fetches the tor exit node list from https://check.torproject.org/exit-addresses and parses all the IPs into a list, then checks if the user's IP address is in...
23,933
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/plugins/tracker_url_remover.py
22,23
1,43
on_result
23,43
23,43
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import re from urllib.parse import urlunparse, parse_qsl, urlencode from flask_babel import gettext regexes = { re.compile(r'utm_[^&]+'), re.compile(r'(wkey|wemail)[^&]*'), re.compile(r'(_hsenc|_hsmi|hsCtaTracking|__h...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import re from urllib.parse import urlunparse, parse_qsl, urlencode from flask_babel import gettext regexes = { re.compile(r'utm_[^&]+'), re.compile(r'(wkey|wemail)[^&]*'), re.compile(r'(_hsenc|_hsmi|hsCtaTracking|__h...
if 'parsed_url' not in result: return True query = result['parsed_url'].query if query == "": return True parsed_query = parse_qsl(query) changes = 0 for i, (param_name, _) in enumerate(list(parsed_query)): for reg in regexes: if reg.match(param_name): ...
if 'parsed_url' not in result: return True query = result['parsed_url'].query if query == "": return True parsed_query = parse_qsl(query) changes = 0 for i, (param_name, _) in enumerate(list(parsed_query)): for reg in regexes: if reg.match(param_name): ...
49
235
197
432
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import re from urllib.parse import urlunparse, parse_qsl, urlencode from flask_babel import gettext regexes = { re.compile(r'utm_[^&]+'), re.compile(r'(wkey|wemail)[^&]*'), re.compile(r'(_hsenc|_hsmi|hsCtaTracking|__h...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import re from urllib.parse import urlunparse, parse_qsl, urlencode from flask_babel import gettext regexes = { re.compile(r'utm_[^&]+'), re.compile(r'(wkey|wemail)[^&]*'), re.compile(r'(_hsenc|_hsmi|hsCtaTracking|__h...
23,934
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/plugins/unit_converter.py
20,21
1,77
_parse_text_and_convert
21,58
21,58
# SPDX-License-Identifier: AGPL-3.0-or-later """Calculate mathematical expressions using ack#eval """ from flask_babel import gettext from searx.data import WIKIDATA_UNITS name = "Unit converter plugin" description = gettext("Convert between units") default_on = True CONVERT_KEYWORDS = ["in", "to", "as"] def _con...
# SPDX-License-Identifier: AGPL-3.0-or-later """Calculate mathematical expressions using ack#eval """ from flask_babel import gettext from searx.data import WIKIDATA_UNITS name = "Unit converter plugin" description = gettext("Convert between units") default_on = True CONVERT_KEYWORDS = ["in", "to", "as"] def _con...
if len(splitted_query) != 2 or splitted_query[0].strip() == "" or splitted_query[1].strip() == "": return from_value = "" from_unit_key = "" # only parse digits as value that belong together read_alpha = False for c in splitted_query[0]: if not read_alpha and (c in ("-", ".") o...
if len(splitted_query) != 2 or splitted_query[0].strip() == "" or splitted_query[1].strip() == "": return from_value = "" from_unit_key = "" # only parse digits as value that belong together read_alpha = False for c in splitted_query[0]: if not read_alpha and (c in ("-", ".") o...
114
332
407
739
# SPDX-License-Identifier: AGPL-3.0-or-later """Calculate mathematical expressions using ack#eval """ from flask_babel import gettext from searx.data import WIKIDATA_UNITS name = "Unit converter plugin" description = gettext("Convert between units") default_on = True CONVERT_KEYWORDS = ["in", "to", "as"] def _con...
# SPDX-License-Identifier: AGPL-3.0-or-later """Calculate mathematical expressions using ack#eval """ from flask_babel import gettext from searx.data import WIKIDATA_UNITS name = "Unit converter plugin" description = gettext("Convert between units") default_on = True CONVERT_KEYWORDS = ["in", "to", "as"] def _con...
23,935
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/query.py
216,217
178,240
_autocomplete
BangParser
217,240
217,240
class BangParser(QueryPartParser): @staticmethod def check(raw_value): # make sure it's not any bang with double '!!' return raw_value[0] == '!' and (len(raw_value) < 2 or raw_value[1] != '!') def __call__(self, raw_value): value = raw_value[1:].replace('-', ' ').replace('_', ' ') ...
class BangParser(QueryPartParser): @staticmethod def check(raw_value): # make sure it's not any bang with double '!!' return raw_value[0] == '!' and (len(raw_value) < 2 or raw_value[1] != '!') def __call__(self, raw_value): value = raw_value[1:].replace('-', ' ').replace('_', ' ') ...
if not value: # show some example queries for suggestion in ['images', 'wikipedia', 'osm']: if suggestion not in self.raw_text_query.disabled_engines or suggestion in categories: self._add_autocomplete(first_char + suggestion) return ...
if not value: # show some example queries for suggestion in ['images', 'wikipedia', 'osm']: if suggestion not in self.raw_text_query.disabled_engines or suggestion in categories: self._add_autocomplete(first_char + suggestion) return ...
82
434
258
692
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
23,936
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/query.py
171,172
151,178
_autocomplete
ExternalBangParser
172,178
172,178
class ExternalBangParser(QueryPartParser): @staticmethod def check(raw_value): return raw_value.startswith('!!') and len(raw_value) > 2 def __call__(self, raw_value): value = raw_value[2:] found, bang_ac_list = self._parse(value) if len(value) > 0 else (False, []) if self.en...
class ExternalBangParser(QueryPartParser): @staticmethod def check(raw_value): return raw_value.startswith('!!') and len(raw_value) > 2 def __call__(self, raw_value): value = raw_value[2:] found, bang_ac_list = self._parse(value) if len(value) > 0 else (False, []) if self.en...
if not bang_ac_list: bang_ac_list = ['g', 'ddg', 'bing'] for external_bang in bang_ac_list: self._add_autocomplete('!!' + external_bang)
if not bang_ac_list: bang_ac_list = ['g', 'ddg', 'bing'] for external_bang in bang_ac_list: self._add_autocomplete('!!' + external_bang)
15
251
72
323
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
23,937
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/query.py
241,243
240,250
check
FeelingLuckyParser
243,245
243,245
class FeelingLuckyParser(QueryPartParser): @staticmethod def check(raw_value): FILL_FUNC_BODY def __call__(self, raw_value): self.raw_text_query.redirect_to_first_result = True return True
class FeelingLuckyParser(QueryPartParser): @staticmethod def check(raw_value): FILL_FUNC_BODY def __call__(self, raw_value): self.raw_text_query.redirect_to_first_result = True return True
return raw_value == '!!'
return raw_value == '!!'
4
74
13
87
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
23,938
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/query.py
84,85
72,151
_parse
LanguageParser
85,118
85,118
class LanguageParser(QueryPartParser): @staticmethod def check(raw_value): return raw_value[0] == ':' def __call__(self, raw_value): value = raw_value[1:].lower().replace('_', '-') found = self._parse(value) if len(value) > 0 else False if self.enable_autocomplete and not fo...
class LanguageParser(QueryPartParser): @staticmethod def check(raw_value): return raw_value[0] == ':' def __call__(self, raw_value): value = raw_value[1:].lower().replace('_', '-') found = self._parse(value) if len(value) > 0 else False if self.enable_autocomplete and not fo...
found = False # check if any language-code is equal with # declared language-codes for lc in sxng_locales: lang_id, lang_name, country, english_name, _flag = map(str.lower, lc) # if correct language-code is found # set it as new search-language ...
found = False # check if any language-code is equal with # declared language-codes for lc in sxng_locales: lang_id, lang_name, country, english_name, _flag = map(str.lower, lc) # if correct language-code is found # set it as new search-language ...
139
542
423
965
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
23,939
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/query.py
38,39
15,43
_add_autocomplete
QueryPartParser
39,43
39,43
class QueryPartParser(ABC): __slots__ = "raw_text_query", "enable_autocomplete" @staticmethod @abstractmethod def check(raw_value): """Check if raw_value can be parsed""" def __init__(self, raw_text_query, enable_autocomplete): self.raw_text_query = raw_text_query self.ena...
class QueryPartParser(ABC): __slots__ = "raw_text_query", "enable_autocomplete" @staticmethod @abstractmethod def check(raw_value): """Check if raw_value can be parsed""" def __init__(self, raw_text_query, enable_autocomplete): self.raw_text_query = raw_text_query self.ena...
if value not in self.raw_text_query.autocomplete_list: self.raw_text_query.autocomplete_list.append(value)
if value not in self.raw_text_query.autocomplete_list: self.raw_text_query.autocomplete_list.append(value)
6
232
48
280
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
23,940
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/query.py
316,317
250,350
changeQuery
RawTextQuery
317,323
317,323
class RawTextQuery: """parse raw text query (the value from the html input)""" PARSER_CLASSES = [ TimeoutParser, # force the timeout LanguageParser, # force a language ExternalBangParser, # external bang (must be before BangParser) BangParser, # force an engine or category ...
class RawTextQuery: """parse raw text query (the value from the html input)""" PARSER_CLASSES = [ TimeoutParser, # force the timeout LanguageParser, # force a language ExternalBangParser, # external bang (must be before BangParser) BangParser, # force an engine or category ...
self.user_query_parts = query.strip().split() self.query = self.getFullQuery() self.autocomplete_location = (self.user_query_parts, len(self.user_query_parts) - 1) self.autocomplete_list = [] return self
self.user_query_parts = query.strip().split() self.query = self.getFullQuery() self.autocomplete_location = (self.user_query_parts, len(self.user_query_parts) - 1) self.autocomplete_list = [] return self
17
1,044
85
1,129
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
23,941
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/query.py
44,46
43,72
check
TimeoutParser
46,48
46,48
class TimeoutParser(QueryPartParser): @staticmethod def check(raw_value): FILL_FUNC_BODY def __call__(self, raw_value): value = raw_value[1:] found = self._parse(value) if len(value) > 0 else False if self.enable_autocomplete and not value: self._autocomplete() ret...
class TimeoutParser(QueryPartParser): @staticmethod def check(raw_value): FILL_FUNC_BODY def __call__(self, raw_value): value = raw_value[1:] found = self._parse(value) if len(value) > 0 else False if self.enable_autocomplete and not value: self._autocomplete() ret...
return raw_value[0] == '<'
return raw_value[0] == '<'
4
306
16
322
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-module-docstring, missing-class-docstring from abc import abstractmethod, ABC import re from searx import settings from searx.sxng_locales import sxng_locales from searx.engines import categories, engines, engine_shortcuts from searx...
23,942
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/redisdb.py
39,40
1,70
initialize
40,70
40,70
# SPDX-License-Identifier: AGPL-3.0-or-later """Implementation of the redis client (redis-py_). .. _redis-py: https://github.com/redis/redis-py This implementation uses the :ref:`settings redis` setup from ``settings.yml``. A redis DB connect can be tested by:: >>> from searx import redisdb >>> redisdb.initializ...
# SPDX-License-Identifier: AGPL-3.0-or-later """Implementation of the redis client (redis-py_). .. _redis-py: https://github.com/redis/redis-py This implementation uses the :ref:`settings redis` setup from ``settings.yml``. A redis DB connect can be tested by:: >>> from searx import redisdb >>> redisdb.initializ...
global _CLIENT # pylint: disable=global-statement redis_url = get_setting('redis.url') if not redis_url: return False try: # create a client, but no connection is done _CLIENT = redis.Redis.from_url(redis_url) # log the parameters as seen by the redis lib, without the p...
global _CLIENT # pylint: disable=global-statement redis_url = get_setting('redis.url') if not redis_url: return False try: # create a client, but no connection is done _CLIENT = redis.Redis.from_url(redis_url) # log the parameters as seen by the redis lib, without the p...
133
299
428
727
# SPDX-License-Identifier: AGPL-3.0-or-later """Implementation of the redis client (redis-py_). .. _redis-py: https://github.com/redis/redis-py This implementation uses the :ref:`settings redis` setup from ``settings.yml``. A redis DB connect can be tested by:: >>> from searx import redisdb >>> redisdb.initializ...
# SPDX-License-Identifier: AGPL-3.0-or-later """Implementation of the redis client (redis-py_). .. _redis-py: https://github.com/redis/redis-py This implementation uses the :ref:`settings redis` setup from ``settings.yml``. A redis DB connect can be tested by:: >>> from searx import redisdb >>> redisdb.initializ...
23,946
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/checker/__main__.py
64,65
1,119
run
65,96
65,96
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import sys import io import os import argparse import logging import searx.search import searx.search.checker from searx.search import PROCESSORS from searx.engines import engine_shortcuts # configure logging root = logging.getL...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import sys import io import os import argparse import logging import searx.search import searx.search.checker from searx.search import PROCESSORS from searx.engines import engine_shortcuts # configure logging root = logging.getL...
searx.search.initialize() name_checker_list = [] for name, processor in iter_processor(engine_name_list): stdout.write(f'{BOLD_SEQ}Engine {name:30}{RESET_SEQ}Checking\n') if not sys.stdout.isatty(): stderr.write(f'{BOLD_SEQ}Engine {name:30}{RESET_SEQ}Checking\n') checker ...
searx.search.initialize() name_checker_list = [] for name, processor in iter_processor(engine_name_list): stdout.write(f'{BOLD_SEQ}Engine {name:30}{RESET_SEQ}Checking\n') if not sys.stdout.isatty(): stderr.write(f'{BOLD_SEQ}Engine {name:30}{RESET_SEQ}Checking\n') checker ...
103
873
609
1,482
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import sys import io import os import argparse import logging import searx.search import searx.search.checker from searx.search import PROCESSORS from searx.engines import engine_shortcuts # configure logging root = logging.getL...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import sys import io import os import argparse import logging import searx.search import searx.search.checker from searx.search import PROCESSORS from searx.engines import engine_shortcuts # configure logging root = logging.getL...
23,947
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/checker/background.py
103,104
1,169
run
104,129
104,129
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, cyclic-import import json import time import threading import os import signal from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict, Union import redis.exceptions from searx import logger, settings, searx_debu...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, cyclic-import import json import time import threading import os import signal from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict, Union import redis.exceptions from searx import logger, settings, searx_debu...
try: # use a Redis lock to make sure there is no checker running at the same time # (this should not happen, this is a safety measure) with get_redis_client().lock(REDIS_LOCK_KEY, blocking_timeout=60, timeout=3600): logger.info('Starting checker') result: CheckerOk = ...
try: # use a Redis lock to make sure there is no checker running at the same time # (this should not happen, this is a safety measure) with get_redis_client().lock(REDIS_LOCK_KEY, blocking_timeout=60, timeout=3600): logger.info('Starting checker') result: CheckerOk = ...
97
1,280
356
1,636
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, cyclic-import import json import time import threading import os import signal from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict, Union import redis.exceptions from searx import logger, settings, searx_debu...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, cyclic-import import json import time import threading import os import signal from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict, Union import redis.exceptions from searx import logger, settings, searx_debu...
23,948
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/checker/scheduler.py
28,29
1,59
scheduler_function
39,59
29,59
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring """Lame scheduler which use Redis as a source of truth: * the Redis key SearXNG_checker_next_call_ts contains the next time the embedded checker should run. * to avoid lock, a unique Redis script reads and updates the Redis key Sear...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring """Lame scheduler which use Redis as a source of truth: * the Redis key SearXNG_checker_next_call_ts contains the next time the embedded checker should run. * to avoid lock, a unique Redis script reads and updates the Redis key Sear...
scheduler_now_script = SCHEDULER_LUA.open().read() while True: # ask the Redis script what to do # the script says # * if the checker must run now. # * how to long to way before calling the script again (it can be call earlier, but not later). script = lua_script_storage(...
"""Run the checker periodically. The function never returns. Parameters: * start_after_from and start_after_to: when to call "callback" for the first on the Redis instance * every_from and every_to: after the first call, how often to call "callback" There is no issue: * to call this function i...
104
476
275
751
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring """Lame scheduler which use Redis as a source of truth: * the Redis key SearXNG_checker_next_call_ts contains the next time the embedded checker should run. * to avoid lock, a unique Redis script reads and updates the Redis key Sear...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring """Lame scheduler which use Redis as a source of truth: * the Redis key SearXNG_checker_next_call_ts contains the next time the embedded checker should run. * to avoid lock, a unique Redis script reads and updates the Redis key Sear...
23,949
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/models.py
75,77
27,133
categories
SearchQuery
77,79
77,79
class SearchQuery: """container for all the search parameters (query, language, etc...)""" __slots__ = ( 'query', 'engineref_list', 'lang', 'locale', 'safesearch', 'pageno', 'time_range', 'timeout_limit', 'external_bang', 'engine_d...
class SearchQuery: """container for all the search parameters (query, language, etc...)""" __slots__ = ( 'query', 'engineref_list', 'lang', 'locale', 'safesearch', 'pageno', 'time_range', 'timeout_limit', 'external_bang', 'engine_d...
return list(set(map(lambda engineref: engineref.category, self.engineref_list)))
return list(set(map(lambda engineref: engineref.category, self.engineref_list)))
5
962
28
990
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import typing import babel class EngineRef: """Reference by names to an engine and category""" __slots__ = 'name', 'category' def __init__(self, name: str, category: str): self.name = name self.categ...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring import typing import babel class EngineRef: """Reference by names to an engine and category""" __slots__ = 'name', 'category' def __init__(self, name: str, category: str): self.name = name self.categ...
23,950
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/processors/abstract.py
138,139
58,195
get_params
EngineProcessor
147,182
139,182
class EngineProcessor(ABC): """Base classes used for all types of request processors.""" __slots__ = 'engine', 'engine_name', 'lock', 'suspended_status', 'logger' def __init__(self, engine, engine_name: str): self.engine = engine self.engine_name = engine_name self.logger = engines...
class EngineProcessor(ABC): """Base classes used for all types of request processors.""" __slots__ = 'engine', 'engine_name', 'lock', 'suspended_status', 'logger' def __init__(self, engine, engine_name: str): self.engine = engine self.engine_name = engine_name self.logger = engines...
# if paging is not supported, skip if search_query.pageno > 1 and not self.engine.paging: return None # if max page is reached, skip max_page = self.engine.max_page or settings['search']['max_page'] if max_page and max_page < search_query.pageno: return N...
"""Returns a set of (see :ref:`request params <engine request arguments>`) or ``None`` if request is not supported. Not supported conditions (``None`` is returned): - A page-number > 1 when engine does not support paging. - A time range when the engine does not support time ran...
133
1,269
416
1,685
# SPDX-License-Identifier: AGPL-3.0-or-later """Abstract base classes for engine request processors. """ import threading from abc import abstractmethod, ABC from timeit import default_timer from typing import Dict, Union from searx import settings, logger from searx.engines import engines from searx.network import ...
# SPDX-License-Identifier: AGPL-3.0-or-later """Abstract base classes for engine request processors. """ import threading from abc import abstractmethod, ABC from timeit import default_timer from typing import Dict, Union from searx import settings, logger from searx.engines import engines from searx.network import ...
23,951
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/processors/abstract.py
50,51
22,58
resume
SuspendedStatus
51,58
51,58
class SuspendedStatus: """Class to handle suspend state.""" __slots__ = 'suspend_end_time', 'suspend_reason', 'continuous_errors', 'lock' def __init__(self): self.lock = threading.Lock() self.continuous_errors = 0 self.suspend_end_time = 0 self.suspend_reason = None @p...
class SuspendedStatus: """Class to handle suspend state.""" __slots__ = 'suspend_end_time', 'suspend_reason', 'continuous_errors', 'lock' def __init__(self): self.lock = threading.Lock() self.continuous_errors = 0 self.suspend_end_time = 0 self.suspend_reason = None @p...
with self.lock: # reset the suspend variables self.continuous_errors = 0 self.suspend_end_time = 0 self.suspend_reason = None
with self.lock: # reset the suspend variables self.continuous_errors = 0 self.suspend_end_time = 0 self.suspend_reason = None
16
300
55
355
# SPDX-License-Identifier: AGPL-3.0-or-later """Abstract base classes for engine request processors. """ import threading from abc import abstractmethod, ABC from timeit import default_timer from typing import Dict, Union from searx import settings, logger from searx.engines import engines from searx.network import ...
# SPDX-License-Identifier: AGPL-3.0-or-later """Abstract base classes for engine request processors. """ import threading from abc import abstractmethod, ABC from timeit import default_timer from typing import Dict, Union from searx import settings, logger from searx.engines import engines from searx.network import ...
23,952
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/processors/offline.py
14,15
9,27
_search_basic
OfflineProcessor
15,17
15,17
class OfflineProcessor(EngineProcessor): """Processor class used by ``offline`` engines""" engine_type = 'offline' def _search_basic(self, query, params): FILL_FUNC_BODY def search(self, query, params, result_container, start_time, timeout_limit): try: search_results = self._search_...
class OfflineProcessor(EngineProcessor): """Processor class used by ``offline`` engines""" engine_type = 'offline' def _search_basic(self, query, params): FILL_FUNC_BODY def search(self, query, params, result_container, start_time, timeout_limit): try: search_results = self._search_...
return self.engine.search(query, params)
return self.engine.search(query, params)
3
229
16
245
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``offline`` """ from .abstract import EngineProcessor class OfflineProcessor(EngineProcessor): """Processor class used by ``offline`` engines""" engine_type = 'offline' def _search_basic(self, query, params): FILL_FUNC_BODY ...
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``offline`` """ from .abstract import EngineProcessor class OfflineProcessor(EngineProcessor): """Processor class used by ``offline`` engines""" engine_type = 'offline' def _search_basic(self, query, params): FILL_FUNC_BODY ...
23,955
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/processors/online_currency.py
15,16
1,74
normalize_name
16,21
16,21
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_currency`` """ import unicodedata import re from searx.data import CURRENCIES from .online import OnlineProcessor parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I) def normalize_name(name): FIL...
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_currency`` """ import unicodedata import re from searx.data import CURRENCIES from .online import OnlineProcessor parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I) def normalize_name(name): FIL...
name = name.lower().replace('-', ' ').rstrip('s') name = re.sub(' +', ' ', name) return unicodedata.normalize('NFKD', name).lower()
name = name.lower().replace('-', ' ').rstrip('s') name = re.sub(' +', ' ', name) return unicodedata.normalize('NFKD', name).lower()
15
665
60
725
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_currency`` """ import unicodedata import re from searx.data import CURRENCIES from .online import OnlineProcessor parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I) def normalize_name(name): FIL...
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_currency`` """ import unicodedata import re from searx.data import CURRENCIES from .online import OnlineProcessor parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I) def normalize_name(name): FIL...
23,956
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/processors/online_currency.py
38,39
33,74
get_params
OnlineCurrencyProcessor
41,65
39,65
class OnlineCurrencyProcessor(OnlineProcessor): """Processor class used by ``online_currency`` engines.""" engine_type = 'online_currency' def get_params(self, search_query, engine_category): FILL_FUNC_BODY def get_default_tests(self): tests = {} tests['currency'] = { 'matr...
class OnlineCurrencyProcessor(OnlineProcessor): """Processor class used by ``online_currency`` engines.""" engine_type = 'online_currency' def get_params(self, search_query, engine_category): """Returns a set of :ref:`request params <engine request online_currency>` or ``None`` if search q...
params = super().get_params(search_query, engine_category) if params is None: return None m = parser_re.match(search_query.query) if not m: return None amount_str, from_currency, to_currency = m.groups() try: amount = float(amount_st...
"""Returns a set of :ref:`request params <engine request online_currency>` or ``None`` if search query does not match to :py:obj:`parser_re`.""" params = super().get_params(search_query, engine_category) if params is None: return None m = parser_re.match(search_quer...
56
172
256
428
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_currency`` """ import unicodedata import re from searx.data import CURRENCIES from .online import OnlineProcessor parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I) def normalize_name(name): ...
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_currency`` """ import unicodedata import re from searx.data import CURRENCIES from .online import OnlineProcessor parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I) def normalize_name(name): ...
23,957
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/processors/online_dictionary.py
19,20
14,61
get_params
OnlineDictionaryProcessor
23,45
20,45
class OnlineDictionaryProcessor(OnlineProcessor): """Processor class used by ``online_dictionary`` engines.""" engine_type = 'online_dictionary' def get_params(self, search_query, engine_category): FILL_FUNC_BODY def get_default_tests(self): tests = {} if getattr(self.engine, 'paging',...
class OnlineDictionaryProcessor(OnlineProcessor): """Processor class used by ``online_dictionary`` engines.""" engine_type = 'online_dictionary' def get_params(self, search_query, engine_category): """Returns a set of :ref:`request params <engine request online_dictionary>` or ``None`` if ...
params = super().get_params(search_query, engine_category) if params is None: return None m = parser_re.match(search_query.query) if not m: return None from_lang, to_lang, query = m.groups() from_lang = is_valid_lang(from_lang) to_lang =...
"""Returns a set of :ref:`request params <engine request online_dictionary>` or ``None`` if search query does not match to :py:obj:`parser_re`. """ params = super().get_params(search_query, engine_category) if params is None: return None m = parser_re.match(s...
48
278
185
463
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_dictionary`` """ import re from searx.utils import is_valid_lang from .online import OnlineProcessor parser_re = re.compile('.*?([a-z]+)-([a-z]+) (.+)$', re.I) class OnlineDictionaryProcessor(OnlineProcessor): """Processor cl...
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_dictionary`` """ import re from searx.utils import is_valid_lang from .online import OnlineProcessor parser_re = re.compile('.*?([a-z]+)-([a-z]+) (.+)$', re.I) class OnlineDictionaryProcessor(OnlineProcessor): """Processor cl...
23,958
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/search/processors/online_url_search.py
21,22
16,46
get_params
OnlineUrlSearchProcessor
25,46
22,46
class OnlineUrlSearchProcessor(OnlineProcessor): """Processor class used by ``online_url_search`` engines.""" engine_type = 'online_url_search' def get_params(self, search_query, engine_category): FILL_FUNC_BODY
class OnlineUrlSearchProcessor(OnlineProcessor): """Processor class used by ``online_url_search`` engines.""" engine_type = 'online_url_search' def get_params(self, search_query, engine_category): """Returns a set of :ref:`request params <engine request online>` or ``None`` if search query...
params = super().get_params(search_query, engine_category) if params is None: return None url_match = False search_urls = {} for k, v in re_search_urls.items(): m = v.search(search_query.query) v = None if m: url_...
"""Returns a set of :ref:`request params <engine request online>` or ``None`` if search query does not match to :py:obj:`re_search_urls`. """ params = super().get_params(search_query, engine_category) if params is None: return None url_match = False ...
48
116
166
282
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_url_search`` """ import re from .online import OnlineProcessor re_search_urls = { 'http': re.compile(r'https?:\/\/[^ ]*'), 'ftp': re.compile(r'ftps?:\/\/[^ ]*'), 'data:image': re.compile('data:image/[^; ]*;base64,[^ ]*')...
# SPDX-License-Identifier: AGPL-3.0-or-later """Processors for engine-type: ``online_url_search`` """ import re from .online import OnlineProcessor re_search_urls = { 'http': re.compile(r'https?:\/\/[^ ]*'), 'ftp': re.compile(r'ftps?:\/\/[^ ]*'), 'data:image': re.compile('data:image/[^; ]*;base64,[^ ]*')...
23,959
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/settings_loader.py
60,61
1,151
update_dict
61,69
61,69
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, too-many-branches from typing import Optional from os import environ from os.path import dirname, join, abspath, isfile from collections.abc import Mapping from itertools import filterfalse import yaml from searx.exceptions impo...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, too-many-branches from typing import Optional from os import environ from os.path import dirname, join, abspath, isfile from collections.abc import Mapping from itertools import filterfalse import yaml from searx.exceptions impo...
for k, v in user_dict.items(): if isinstance(v, Mapping): default_dict[k] = update_dict(default_dict.get(k, {}), v) else: default_dict[k] = v return default_dict
for k, v in user_dict.items(): if isinstance(v, Mapping): default_dict[k] = update_dict(default_dict.get(k, {}), v) else: default_dict[k] = v return default_dict
19
1,584
79
1,663
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, too-many-branches from typing import Optional from os import environ from os.path import dirname, join, abspath, isfile from collections.abc import Mapping from itertools import filterfalse import yaml from searx.exceptions impo...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, too-many-branches from typing import Optional from os import environ from os.path import dirname, join, abspath, isfile from collections.abc import Mapping from itertools import filterfalse import yaml from searx.exceptions impo...
23,961
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/utils.py
121,122
91,146
handle_charref
_HTMLTextExtractor
122,130
122,130
class _HTMLTextExtractor(HTMLParser): """Internal class to extract text from HTML""" def __init__(self): HTMLParser.__init__(self) self.result = [] self.tags = [] def handle_starttag(self, tag, attrs): self.tags.append(tag) if tag == 'br': self.result.ap...
class _HTMLTextExtractor(HTMLParser): """Internal class to extract text from HTML""" def __init__(self): HTMLParser.__init__(self) self.result = [] self.tags = [] def handle_starttag(self, tag, attrs): self.tags.append(tag) if tag == 'br': self.result.ap...
if not self.is_valid_tag(): return if name[0] in ('x', 'X'): codepoint = int(name[1:], 16) else: codepoint = int(name) self.result.append(chr(codepoint))
if not self.is_valid_tag(): return if name[0] in ('x', 'X'): codepoint = int(name[1:], 16) else: codepoint = int(name) self.result.append(chr(codepoint))
18
402
85
487
# SPDX-License-Identifier: AGPL-3.0-or-later """Utility functions for the engines """ import re import importlib import importlib.util import json import types from typing import Optional, Union, Any, Set, List, Dict, MutableMapping, Tuple, Callable from numbers import Number from os.path import splitext, join from r...
# SPDX-License-Identifier: AGPL-3.0-or-later """Utility functions for the engines """ import re import importlib import importlib.util import json import types from typing import Optional, Union, Any, Set, List, Dict, MutableMapping, Tuple, Callable from numbers import Number from os.path import splitext, join from r...
23,962
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/version.py
43,44
1,133
get_git_url_and_branch
44,60
44,60
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=,missing-module-docstring,missing-class-docstring import os import shlex import subprocess import logging import importlib # fallback values # if there is searx.version_frozen module, and it is not possible to get the git tag VERSION_STRING = "1.0.0" VERS...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=,missing-module-docstring,missing-class-docstring import os import shlex import subprocess import logging import importlib # fallback values # if there is searx.version_frozen module, and it is not possible to get the git tag VERSION_STRING = "1.0.0" VERS...
try: ref = subprocess_run("git rev-parse --abbrev-ref @{upstream}") except subprocess.CalledProcessError: ref = subprocess_run("git rev-parse --abbrev-ref master@{upstream}") origin, git_branch = ref.split("/", 1) git_url = subprocess_run(["git", "remote", "get-url", origin]) # get ...
try: ref = subprocess_run("git rev-parse --abbrev-ref @{upstream}") except subprocess.CalledProcessError: ref = subprocess_run("git rev-parse --abbrev-ref master@{upstream}") origin, git_branch = ref.split("/", 1) git_url = subprocess_run(["git", "remote", "get-url", origin]) # get ...
52
1,440
224
1,664
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=,missing-module-docstring,missing-class-docstring import os import shlex import subprocess import logging import importlib # fallback values # if there is searx.version_frozen module, and it is not possible to get the git tag VERSION_STRING = "1.0.0" VERS...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=,missing-module-docstring,missing-class-docstring import os import shlex import subprocess import logging import importlib # fallback values # if there is searx.version_frozen module, and it is not possible to get the git tag VERSION_STRING = "1.0.0" VERS...
23,965
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/webutils.py
96,97
85,113
writerow
CSVWriter
97,108
97,108
class CSVWriter: """A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding.""" def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = StringIO() self.writer = csv.writer(self.queue, dialect=di...
class CSVWriter: """A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding.""" def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = StringIO() self.writer = csv.writer(self.queue, dialect=di...
self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.strip('\x00') # ... and re-encode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data.de...
self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.strip('\x00') # ... and re-encode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data.de...
38
179
124
303
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, invalid-name from __future__ import annotations import os import pathlib import csv import hashlib import hmac import re import inspect import itertools import json from datetime import datetime, timedelta from typing import Iter...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, invalid-name from __future__ import annotations import os import pathlib import csv import hashlib import hmac import re import inspect import itertools import json from datetime import datetime, timedelta from typing import Iter...
23,966
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/webutils.py
149,150
148,159
default
JSONEncoder
150,159
150,159
class JSONEncoder(json.JSONEncoder): # pylint: disable=missing-class-docstring def default(self, o): FILL_FUNC_BODY
class JSONEncoder(json.JSONEncoder): # pylint: disable=missing-class-docstring def default(self, o): FILL_FUNC_BODY
if isinstance(o, datetime): return o.isoformat() if isinstance(o, timedelta): return o.total_seconds() if isinstance(o, set): return list(o) return super().default(o)
if isinstance(o, datetime): return o.isoformat() if isinstance(o, timedelta): return o.total_seconds() if isinstance(o, set): return list(o) return super().default(o)
17
46
76
122
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, invalid-name from __future__ import annotations import os import pathlib import csv import hashlib import hmac import re import inspect import itertools import json from datetime import datetime, timedelta from typing import Iter...
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-module-docstring, invalid-name from __future__ import annotations import os import pathlib import csv import hashlib import hmac import re import inspect import itertools import json from datetime import datetime, timedelta from typing import Iter...
23,968
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searxng_extra/update/update_currencies.py
100,101
1,158
fetch_db
101,133
101,133
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch currencies from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/currencies.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ # pylint: disable=invalid-name import re import unicodedat...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch currencies from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/currencies.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ # pylint: disable=invalid-name import re import unicodedat...
db = { 'names': {}, 'iso4217': {}, } for r in wikidata_request_result_iterator(SPARQL_WIKIPEDIA_NAMES_REQUEST): iso4217 = r['iso4217']['value'] article_name = r['article_name']['value'] article_lang = r['article_name']['xml:lang'] add_currency_name(db, articl...
db = { 'names': {}, 'iso4217': {}, } for r in wikidata_request_result_iterator(SPARQL_WIKIPEDIA_NAMES_REQUEST): iso4217 = r['iso4217']['value'] article_name = r['article_name']['value'] article_lang = r['article_name']['xml:lang'] add_currency_name(db, articl...
77
1,547
422
1,969
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch currencies from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/currencies.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ # pylint: disable=invalid-name import re import unicodedat...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch currencies from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/currencies.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ # pylint: disable=invalid-name import re import unicodedat...
23,970
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searxng_extra/update/update_external_bangs.py
96,97
1,144
parse_ddg_bangs
97,142
97,142
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update :origin:`searx/data/external_bangs.json` using the duckduckgo bangs from :py:obj:`BANGS_URL`. - :origin:`CI Update data ... <.github/workflows/data-update.yml>` """ import json import httpx from searx.external_bang import LEAF_KEY from sea...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update :origin:`searx/data/external_bangs.json` using the duckduckgo bangs from :py:obj:`BANGS_URL`. - :origin:`CI Update data ... <.github/workflows/data-update.yml>` """ import json import httpx from searx.external_bang import LEAF_KEY from sea...
bang_trie = {} bang_urls = {} for bang_definition in ddg_bangs: # bang_list bang_url = bang_definition['u'] if '{{{s}}}' not in bang_url: # ignore invalid bang continue bang_url = bang_url.replace('{{{s}}}', chr(2)) # only for the https prot...
bang_trie = {} bang_urls = {} for bang_definition in ddg_bangs: # bang_list bang_url = bang_definition['u'] if '{{{s}}}' not in bang_url: # ignore invalid bang continue bang_url = bang_url.replace('{{{s}}}', chr(2)) # only for the https prot...
150
895
595
1,490
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update :origin:`searx/data/external_bangs.json` using the duckduckgo bangs from :py:obj:`BANGS_URL`. - :origin:`CI Update data ... <.github/workflows/data-update.yml>` """ import json import httpx from searx.external_bang import LEAF_KEY from sea...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update :origin:`searx/data/external_bangs.json` using the duckduckgo bangs from :py:obj:`BANGS_URL`. - :origin:`CI Update data ... <.github/workflows/data-update.yml>` """ import json import httpx from searx.external_bang import LEAF_KEY from sea...
23,971
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searxng_extra/update/update_locales.py
31,32
1,103
main
32,68
32,68
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update locale names in :origin:`searx/data/locales.json` used by :ref:`searx.locales` - :py:obj:`searx.locales.RTL_LOCALES` - :py:obj:`searx.locales.LOCALE_NAMES` """ # pylint: disable=invalid-name from __future__ import annotations from typing imp...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update locale names in :origin:`searx/data/locales.json` used by :ref:`searx.locales` - :py:obj:`searx.locales.RTL_LOCALES` - :py:obj:`searx.locales.LOCALE_NAMES` """ # pylint: disable=invalid-name from __future__ import annotations from typing imp...
LOCALE_NAMES = {} RTL_LOCALES: Set[str] = set() for tag, descr in ADDITIONAL_TRANSLATIONS.items(): locale = babel.Locale.parse(LOCALE_BEST_MATCH[tag], sep='-') LOCALE_NAMES[tag] = descr if locale.text_direction == 'rtl': RTL_LOCALES.add(tag) for tag in LOCALE_BEST_...
LOCALE_NAMES = {} RTL_LOCALES: Set[str] = set() for tag, descr in ADDITIONAL_TRANSLATIONS.items(): locale = babel.Locale.parse(LOCALE_BEST_MATCH[tag], sep='-') LOCALE_NAMES[tag] = descr if locale.text_direction == 'rtl': RTL_LOCALES.add(tag) for tag in LOCALE_BEST_...
92
749
498
1,247
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update locale names in :origin:`searx/data/locales.json` used by :ref:`searx.locales` - :py:obj:`searx.locales.RTL_LOCALES` - :py:obj:`searx.locales.LOCALE_NAMES` """ # pylint: disable=invalid-name from __future__ import annotations from typing imp...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update locale names in :origin:`searx/data/locales.json` used by :ref:`searx.locales` - :py:obj:`searx.locales.RTL_LOCALES` - :py:obj:`searx.locales.LOCALE_NAMES` """ # pylint: disable=invalid-name from __future__ import annotations from typing imp...
23,973
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searxng_extra/update/update_pygments.py
58,59
1,73
generat_css
59,69
59,69
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update pygments style Call this script after each upgrade of pygments """ # pylint: disable=too-few-public-methods from pathlib import Path import pygments from pygments.formatters.html import HtmlFormatter from searx import searx_dir LESS_FILE ...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update pygments style Call this script after each upgrade of pygments """ # pylint: disable=too-few-public-methods from pathlib import Path import pygments from pygments.formatters.html import HtmlFormatter from searx import searx_dir LESS_FILE ...
css = HEADER + START_LIGHT_THEME for line in Formatter(style=light_style).get_style_lines(): css += '\n ' + line css += END_LIGHT_THEME + START_DARK_THEME for line in Formatter(style=dark_style).get_style_lines(): css += '\n ' + line css += END_DARK_THEME return css
css = HEADER + START_LIGHT_THEME for line in Formatter(style=light_style).get_style_lines(): css += '\n ' + line css += END_LIGHT_THEME + START_DARK_THEME for line in Formatter(style=dark_style).get_style_lines(): css += '\n ' + line css += END_DARK_THEME return css
35
516
123
639
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update pygments style Call this script after each upgrade of pygments """ # pylint: disable=too-few-public-methods from pathlib import Path import pygments from pygments.formatters.html import HtmlFormatter from searx import searx_dir LESS_FILE ...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update pygments style Call this script after each upgrade of pygments """ # pylint: disable=too-few-public-methods from pathlib import Path import pygments from pygments.formatters.html import HtmlFormatter from searx import searx_dir LESS_FILE ...
23,974
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searxng_extra/update/update_pygments.py
50,51
45,58
get_style_lines
Formatter
51,58
51,58
class Formatter(HtmlFormatter): # pylint: disable=missing-class-docstring @property def _pre_style(self): return 'line-height: 100%;' def get_style_lines(self, arg=None): FILL_FUNC_BODY
class Formatter(HtmlFormatter): # pylint: disable=missing-class-docstring @property def _pre_style(self): return 'line-height: 100%;' def get_style_lines(self, arg=None): FILL_FUNC_BODY
style_lines = [] style_lines.extend(self.get_linenos_style_defs()) style_lines.extend(self.get_background_style_defs(arg)) style_lines.extend(self.get_token_style_defs(arg)) return style_lines
style_lines = [] style_lines.extend(self.get_linenos_style_defs()) style_lines.extend(self.get_background_style_defs(arg)) style_lines.extend(self.get_token_style_defs(arg)) return style_lines
8
78
85
163
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update pygments style Call this script after each upgrade of pygments """ # pylint: disable=too-few-public-methods from pathlib import Path import pygments from pygments.formatters.html import HtmlFormatter from searx import searx_dir LESS_FILE ...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Update pygments style Call this script after each upgrade of pygments """ # pylint: disable=too-few-public-methods from pathlib import Path import pygments from pygments.formatters.html import HtmlFormatter from searx import searx_dir LESS_FILE ...
23,975
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searxng_extra/update/update_wikidata_units.py
55,56
1,84
get_data
56,77
56,77
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch units from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/wikidata_units.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ import json import collections # set path from os.path imp...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch units from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/wikidata_units.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ import json import collections # set path from os.path imp...
results = collections.OrderedDict() response = wikidata.send_wikidata_query(SARQL_REQUEST) for unit in response['results']['bindings']: symbol = unit['symbol']['value'] name = unit['item']['value'].rsplit('/', 1)[1] si_name = unit.get('tosiUnit', {}).get('value', '') if si_n...
results = collections.OrderedDict() response = wikidata.send_wikidata_query(SARQL_REQUEST) for unit in response['results']['bindings']: symbol = unit['symbol']['value'] name = unit['item']['value'].rsplit('/', 1)[1] si_name = unit.get('tosiUnit', {}).get('value', '') if si_n...
66
745
257
1,002
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch units from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/wikidata_units.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ import json import collections # set path from os.path imp...
#!/usr/bin/env python # SPDX-License-Identifier: AGPL-3.0-or-later """Fetch units from :origin:`searx/engines/wikidata.py` engine. Output file: :origin:`searx/data/wikidata_units.json` (:origin:`CI Update data ... <.github/workflows/data-update.yml>`). """ import json import collections # set path from os.path imp...
23,976
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng
/home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/utils/get_setting.py
15,16
1,124
main
16,23
16,23
# SPDX-License-Identifier: AGPL-3.0-or-later """build environment used by shell scripts """ # set path import sys import importlib.util import re from pathlib import Path repo_root = Path(__file__).resolve().parent.parent def main(setting_name): FILL_FUNC_BODYdef get_setting_value(settings, name): value = sett...
# SPDX-License-Identifier: AGPL-3.0-or-later """build environment used by shell scripts """ # set path import sys import importlib.util import re from pathlib import Path repo_root = Path(__file__).resolve().parent.parent def main(setting_name): FILL_FUNC_BODYdef get_setting_value(settings, name): value = sett...
settings_path = repo_root / "searx" / "settings.yml" with open(settings_path) as f: settings = parse_yaml(f.read()) print(get_setting_value(settings, setting_name))
settings_path = repo_root / "searx" / "settings.yml" with open(settings_path) as f: settings = parse_yaml(f.read()) print(get_setting_value(settings, setting_name))
16
1,038
73
1,111
# SPDX-License-Identifier: AGPL-3.0-or-later """build environment used by shell scripts """ # set path import sys import importlib.util import re from pathlib import Path repo_root = Path(__file__).resolve().parent.parent def main(setting_name): FILL_FUNC_BODYdef get_setting_value(settings, name): value = sett...
# SPDX-License-Identifier: AGPL-3.0-or-later """build environment used by shell scripts """ # set path import sys import importlib.util import re from pathlib import Path repo_root = Path(__file__).resolve().parent.parent def main(setting_name): FILL_FUNC_BODYdef get_setting_value(settings, name): value = sett...
24,038
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/airquality/air_quality_aqicn.py
26,27
1,69
get_air_quality
34,65
27,65
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-09-30 17:58 Introduction: 获取空气质量 官网:http://aqicn.org/here/ """ import requests # token,申请地址:http://aqicn.org/data-platform/token/#/ AQICN_TOKEN = '6382db85ef321ae81f316486de0b5b8aa6c84f62' AIR_STATUS_DICT = { 50:...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-09-30 17:58 Introduction: 获取空气质量 官网:http://aqicn.org/here/ """ import requests # token,申请地址:http://aqicn.org/data-platform/token/#/ AQICN_TOKEN = '6382db85ef321ae81f316486de0b5b8aa6c84f62' AIR_STATUS_DICT = { 50:...
if not city or not city.strip(): return print('获取 {} 的空气质量...'.format(city)) try: url = 'http://api.waqi.info/feed/{city}/?token={token}'.format(city=city, token=AQICN_TOKEN) resp = requests.get(url) if resp.status_code == 200: # print(resp.text) con...
""" 通过城市名获取空气质量 官网:http://aqicn.org/here/ token 申请地址:http://aqicn.org/data-platform/token/#/ :param city: 城市 :return: """ if not city or not city.strip(): return print('获取 {} 的空气质量...'.format(city)) try: url = 'http://api.waqi.info/feed/{city}/?token={token}'.fo...
75
360
375
735
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-09-30 17:58 Introduction: 获取空气质量 官网:http://aqicn.org/here/ """ import requests # token,申请地址:http://aqicn.org/data-platform/token/#/ AQICN_TOKEN = '6382db85ef321ae81f316486de0b5b8aa6c84f62' AIR_STATUS_DICT = { 50:...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-09-30 17:58 Introduction: 获取空气质量 官网:http://aqicn.org/here/ """ import requests # token,申请地址:http://aqicn.org/data-platform/token/#/ AQICN_TOKEN = '6382db85ef321ae81f316486de0b5b8aa6c84f62' AIR_STATUS_DICT = { 50:...
24,039
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/bot/ownthink_robot.py
20,21
1,68
get_ownthink_robot
28,61
21,61
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-27 11:37 Introduction: 思知机器人,接口地址:<https://www.ownthink.com/> userid 可为空 """ import re import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-27 11:37 Introduction: 思知机器人,接口地址:<https://www.ownthink.com/> userid 可为空 """ import re import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['...
try: # config.init() info = config.get('auto_reply_info')['txapi_conf'] app_key = info.get('app_key', '') if not re.findall(r'^[0-9a-z]{20,}$', app_key): # 验证 app_key 是否有效 app_key = '' params = { 'appid': app_key, 'userid': md5_encode(use...
""" 思知机器人,接口地址:<https://www.ownthink.com/> https://api.ownthink.com/bot?appid=xiaosi&userid=user&spoken=姚明多高啊? :param text: 发出的消息 :param userid: 收到的内容 :return: """ try: # config.init() info = config.get('auto_reply_info')['txapi_conf'] app_key = info.get('app_key'...
75
352
359
711
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-27 11:37 Introduction: 思知机器人,接口地址:<https://www.ownthink.com/> userid 可为空 """ import re import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-27 11:37 Introduction: 思知机器人,接口地址:<https://www.ownthink.com/> userid 可为空 """ import re import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['...
24,040
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/bot/qingyunke.py
17,18
1,51
get_qingyunke
24,43
18,43
# coding=utf-8 """ http://api.qingyunke.com/ 青云客智能聊天机器人API 可直接使用 """ import requests __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 3 BOT_NAME = '青云客机器人' URL = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}' def get_qingyunke(text, userid=''): FILL_FUNC_BODYget_auto_reply = get_qingyu...
# coding=utf-8 """ http://api.qingyunke.com/ 青云客智能聊天机器人API 可直接使用 """ import requests __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 3 BOT_NAME = '青云客机器人' URL = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}' def get_qingyunke(text, userid=''): """ 青云客智能聊天机器人API http://api.qing...
try: # print('发出消息:{}'.format(text)) resp = requests.get(URL.format(text)) if resp.status_code == 200: # print(resp.text) re_data = resp.json() if re_data['result'] == 0: return_text = re_data['content'] return return_text ...
""" 青云客智能聊天机器人API http://api.qingyunke.com/ :param text: str 聊天 :param userid: str 无用 :return: str """ try: # print('发出消息:{}'.format(text)) resp = requests.get(URL.format(text)) if resp.status_code == 200: # print(resp.text) re_data = resp.json...
35
287
186
473
# coding=utf-8 """ http://api.qingyunke.com/ 青云客智能聊天机器人API 可直接使用 """ import requests __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 3 BOT_NAME = '青云客机器人' URL = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}' def get_qingyunke(text, userid=''): FILL_FUNC_BODYget_auto_reply = get_qingyu...
# coding=utf-8 """ http://api.qingyunke.com/ 青云客智能聊天机器人API 可直接使用 """ import requests __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 3 BOT_NAME = '青云客机器人' URL = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}' def get_qingyunke(text, userid=''): """ 青云客智能聊天机器人API http://api.qing...
24,041
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/bot/qq_nlpchat.py
74,75
1,103
getReqSign
86,94
75,94
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-01 23:49 Introduction: 智能闲聊(腾讯) 官网:https://ai.qq.com/product/nlpchat.shtml 免费试用,得申请 app_id,app_key。 """ import hashlib from urllib import parse import time import random import string import requests from everyday_wechat....
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-01 23:49 Introduction: 智能闲聊(腾讯) 官网:https://ai.qq.com/product/nlpchat.shtml 免费试用,得申请 app_id,app_key。 """ import hashlib from urllib import parse import time import random import string import requests from everyday_wechat....
params = sorted(parser.items()) uri_str = parse.urlencode(params, encoding="UTF-8") sign_str = '{}&app_key={}'.format(uri_str, app_key) # print('sign =', sign_str.strip()) hash_md5 = hashlib.md5(sign_str.encode("UTF-8")) return hash_md5.hexdigest().upper()
''' 获取请求签名,接口鉴权 https://ai.qq.com/doc/auth.shtml 1.将 <key, value> 请求参数对按 key 进行字典升序排序,得到有序的参数对列表 N 2.将列表 N 中的参数对按 URL 键值对的格式拼接成字符串,得到字符串 T(如:key1=value1&key2=value2), URL 键值拼接过程 value 部分需要 URL 编码,URL 编码算法用大写字母,例如 %E8,而不是小写 %e8 3.将应用密钥以 app_key 为键名,组成 URL 键值拼接到字符串 T 末尾,得到字符串 S(如:key1=value1&k...
20
1,158
116
1,274
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-01 23:49 Introduction: 智能闲聊(腾讯) 官网:https://ai.qq.com/product/nlpchat.shtml 免费试用,得申请 app_id,app_key。 """ import hashlib from urllib import parse import time import random import string import requests from everyday_wechat....
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-01 23:49 Introduction: 智能闲聊(腾讯) 官网:https://ai.qq.com/product/nlpchat.shtml 免费试用,得申请 app_id,app_key。 """ import hashlib from urllib import parse import time import random import string import requests from everyday_wechat....
24,042
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/bot/ruyiai.py
21,22
1,64
get_ruyiai_bot
28,56
22,56
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-02 02:46 Introduction: 海知智能 <https://ruyi.ai/> 功能很强大,不仅仅用于聊天。需申请 key,免费 """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_reply',...
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-02 02:46 Introduction: 海知智能 <https://ruyi.ai/> 功能很强大,不仅仅用于聊天。需申请 key,免费 """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_reply',...
try: # config.init() info = config.get('auto_reply_info')['ruyi_conf'] app_key = info['app_key'] if not app_key: print('海知智能 api_key 为空,请求失败') return params = {'q': text, 'user_id': md5_encode(userId), 'app_key': app_key} headers = {'Content-T...
""" 海知智能 文档说明:<http://docs.ruyi.ai/502931> :param text: str 需要发送的话 :param userId: str 用户标识 :return: str 机器人回复 """ try: # config.init() info = config.get('auto_reply_info')['ruyi_conf'] app_key = info['app_key'] if not app_key: print('海知智能 api_key 为...
70
361
329
690
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-02 02:46 Introduction: 海知智能 <https://ruyi.ai/> 功能很强大,不仅仅用于聊天。需申请 key,免费 """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_reply',...
# -*- coding: utf-8 -*- """ Project: HelloWorldPython Creator: DoubleThunder Create time: 2019-07-02 02:46 Introduction: 海知智能 <https://ruyi.ai/> 功能很强大,不仅仅用于聊天。需申请 key,免费 """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_reply',...
24,043
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/bot/tian_robot.py
19,20
1,74
get_tianapi_robot
26,67
20,67
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-02 01:24 Introduction: 天行机器人 申请地址( https://www.tianapi.com/apiview/47 ) """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_re...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-02 01:24 Introduction: 天行机器人 申请地址( https://www.tianapi.com/apiview/47 ) """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_re...
try: # config.init() info = config.get('auto_reply_info')['txapi_conf'] app_key = info['app_key'] if not app_key: print('天行机器人 app_key 为空,请求失败') return reply_name = info.get('reply_name', '') bot_name = info.get('bot_name', '') params ...
""" 从天行机器人获取自动回复,接口地址:<https://www.tianapi.com/apiview/47> :param text: 发出的消息 :param userid: 收到的内容 :return: """ try: # config.init() info = config.get('auto_reply_info')['txapi_conf'] app_key = info['app_key'] if not app_key: print('天行机器人 app_key 为...
96
329
497
826
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-02 01:24 Introduction: 天行机器人 申请地址( https://www.tianapi.com/apiview/47 ) """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_re...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-02 01:24 Introduction: 天行机器人 申请地址( https://www.tianapi.com/apiview/47 ) """ import requests from everyday_wechat.utils import config from everyday_wechat.utils.common import ( md5_encode ) __all__ = ['get_auto_re...
24,044
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/bot/tuling123.py
29,30
1,84
get_tuling123
37,77
30,77
# coding=utf-8 ''' 图灵机器人自动回复 官网:http://www.tuling123.com/ apiKey,userid 需要去官网申请。 ''' import requests from everyday_wechat.utils.common import ( is_json, md5_encode ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 1 BOT_NAME = '图灵机器人' # 图灵机器人错误码集合 T...
# coding=utf-8 ''' 图灵机器人自动回复 官网:http://www.tuling123.com/ apiKey,userid 需要去官网申请。 ''' import requests from everyday_wechat.utils.common import ( is_json, md5_encode ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 1 BOT_NAME = '图灵机器人' # 图灵机器人错误码集合 T...
try: # config.init() info = config.get('auto_reply_info')['turing_conf'] apiKey = info['apiKey'] if not apiKey: print('图灵机器人 apikey 为空,请求出错') return None userId = md5_encode(userId if userId else '250') content = { 'perception': {...
""" 接口地址:(https://www.kancloud.cn/turing/www-tuling123-com/718227) 获取图灵机器人对话 :param text: 发送的话 :param userId: 用户唯一标识(最好用微信好友uuid) :return: 对白 """ try: # config.init() info = config.get('auto_reply_info')['turing_conf'] apiKey = info['apiKey'] if not apiKe...
83
479
393
872
# coding=utf-8 ''' 图灵机器人自动回复 官网:http://www.tuling123.com/ apiKey,userid 需要去官网申请。 ''' import requests from everyday_wechat.utils.common import ( is_json, md5_encode ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 1 BOT_NAME = '图灵机器人' # 图灵机器人错误码集合 T...
# coding=utf-8 ''' 图灵机器人自动回复 官网:http://www.tuling123.com/ apiKey,userid 需要去官网申请。 ''' import requests from everyday_wechat.utils.common import ( is_json, md5_encode ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 1 BOT_NAME = '图灵机器人' # 图灵机器人错误码集合 T...
24,045
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/bot/yigeai.py
22,23
1,66
get_yigeai
30,59
23,59
# """ 『一个AI』自动回复 (http://www.yige.ai/) """ import requests from everyday_wechat.utils.common import ( is_json, md5_encode, ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 2 BOT_NAME = '一个 AI 机器人' # 一个AI错误集合 TULING_ERROR_CODE_LIST = ('501', '502', ...
# """ 『一个AI』自动回复 (http://www.yige.ai/) """ import requests from everyday_wechat.utils.common import ( is_json, md5_encode, ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 2 BOT_NAME = '一个 AI 机器人' # 一个AI错误集合 TULING_ERROR_CODE_LIST = ('501', '502', ...
try: # config.init() info = config.get('auto_reply_info')['yigeai_conf'] token = info['client_token'] if not token: print('一个「AI」token 为空,请求出错') return None session_id = md5_encode(userid if userid else '250') # print('发出的消息:{}'.format(text)) ...
""" 『一个AI』自动回复 (http://www.yige.ai/) 接口说明:http://docs.yige.ai/Query%E6%8E%A5%E5%8F%A3.html :param text:str, 需要发送的话 :userid:str,机器唯一标识 :return:str """ try: # config.init() info = config.get('auto_reply_info')['yigeai_conf'] token = info['client_token'] if n...
78
357
382
739
# """ 『一个AI』自动回复 (http://www.yige.ai/) """ import requests from everyday_wechat.utils.common import ( is_json, md5_encode, ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 2 BOT_NAME = '一个 AI 机器人' # 一个AI错误集合 TULING_ERROR_CODE_LIST = ('501', '502', ...
# """ 『一个AI』自动回复 (http://www.yige.ai/) """ import requests from everyday_wechat.utils.common import ( is_json, md5_encode, ) from everyday_wechat.utils import config __all__ = ['get_auto_reply', 'BOT_INDEX', 'BOT_NAME'] BOT_INDEX = 2 BOT_NAME = '一个 AI 机器人' # 一个AI错误集合 TULING_ERROR_CODE_LIST = ('501', '502', ...
24,046
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/calendar/rt_calendar.py
29,30
1,82
get_rtcalendar
36,74
30,74
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#指定日期的节假日及万年历信息 指定日期的节假日及万年历信息 {"code":1,"msg":"数据返回成功","data":{ "date":"2019-06-27","weekDay":4,"yearTips":"己亥", "type":0,"typeDes":"工作日","chineseZodiac":"猪","solarTerms":"夏至后", "avoid":"移徙.入宅.安葬","lunarCalendar":"五月廿五", "suit":"订盟.纳采.出行.祈福.斋醮.安床.会亲友", "dayOf...
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#指定日期的节假日及万年历信息 指定日期的节假日及万年历信息 {"code":1,"msg":"数据返回成功","data":{ "date":"2019-06-27","weekDay":4,"yearTips":"己亥", "type":0,"typeDes":"工作日","chineseZodiac":"猪","solarTerms":"夏至后", "avoid":"移徙.入宅.安葬","lunarCalendar":"五月廿五", "suit":"订盟.纳采.出行.祈福.斋醮.安床.会亲友", "dayOf...
date_ = date or datetime.now().strftime('%Y%m%d') print('获取 {} 的日历...'.format(date_)) try: resp = requests.get('https://www.mxnzp.com/api/holiday/single/{}'.format(date_)) if resp.status_code == 200: # print(resp.text) content_dict = resp.json() if conte...
""" 获取指定日期的节假日及万年历信息 https://github.com/MZCretin/RollToolsApi#指定日期的节假日及万年历信息 :param data: str 日期 格式 yyyyMMdd :rtype str """ date_ = date or datetime.now().strftime('%Y%m%d') print('获取 {} 的日历...'.format(date_)) try: resp = requests.get('https://www.mxnzp.com/api/holiday/sin...
87
619
439
1,058
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#指定日期的节假日及万年历信息 指定日期的节假日及万年历信息 {"code":1,"msg":"数据返回成功","data":{ "date":"2019-06-27","weekDay":4,"yearTips":"己亥", "type":0,"typeDes":"工作日","chineseZodiac":"猪","solarTerms":"夏至后", "avoid":"移徙.入宅.安葬","lunarCalendar":"五月廿五", "suit":"订盟.纳采.出行.祈福.斋醮.安床.会亲友", "dayOf...
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#指定日期的节假日及万年历信息 指定日期的节假日及万年历信息 {"code":1,"msg":"数据返回成功","data":{ "date":"2019-06-27","weekDay":4,"yearTips":"己亥", "type":0,"typeDes":"工作日","chineseZodiac":"猪","solarTerms":"夏至后", "avoid":"移徙.入宅.安葬","lunarCalendar":"五月廿五", "suit":"订盟.纳采.出行.祈福.斋醮.安床.会亲友", "dayOf...
24,047
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/calendar/sojson_calendar.py
16,17
1,75
get_sojson_calendar
23,67
17,67
# coding=utf-8 """ https://www.sojson.com/api/lunar.html 指定日期的节假日及万年历信息 """ from datetime import datetime import requests from everyday_wechat.utils.common import ( WEEK_DICT, SPIDER_HEADERS ) __all__ = ['get_sojson_calendar'] def get_sojson_calendar(date=''): FILL_FUNC_BODYget_calendar = get_sojson_calendar...
# coding=utf-8 """ https://www.sojson.com/api/lunar.html 指定日期的节假日及万年历信息 """ from datetime import datetime import requests from everyday_wechat.utils.common import ( WEEK_DICT, SPIDER_HEADERS ) __all__ = ['get_sojson_calendar'] def get_sojson_calendar(date=''): """ 获取指定日期的节假日及万年历信息 https://www.so...
date_ = date or datetime.now().strftime('%Y-%m-%d') # print('获取 {} 的日历...'.format(date_)) try: resp = requests.get('https://www.sojson.com/open/api/lunar/json.shtml?date={}'.format(date_), headers=SPIDER_HEADERS) if resp.status_code == 200: """ ...
""" 获取指定日期的节假日及万年历信息 https://www.sojson.com/api/lunar.html :param data: str 日期 格式 %Y-%m-%d :rtype str """ date_ = date or datetime.now().strftime('%Y-%m-%d') # print('获取 {} 的日历...'.format(date_)) try: resp = requests.get('https://www.sojson.com/open/api/lunar/json.shtml?date...
96
269
657
926
# coding=utf-8 """ https://www.sojson.com/api/lunar.html 指定日期的节假日及万年历信息 """ from datetime import datetime import requests from everyday_wechat.utils.common import ( WEEK_DICT, SPIDER_HEADERS ) __all__ = ['get_sojson_calendar'] def get_sojson_calendar(date=''): FILL_FUNC_BODYget_calendar = get_sojson_calendar...
# coding=utf-8 """ https://www.sojson.com/api/lunar.html 指定日期的节假日及万年历信息 """ from datetime import datetime import requests from everyday_wechat.utils.common import ( WEEK_DICT, SPIDER_HEADERS ) __all__ = ['get_sojson_calendar'] def get_sojson_calendar(date=''): """ 获取指定日期的节假日及万年历信息 https://www.so...
24,049
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/horoscope/xzw_horescope.py
33,34
1,76
get_xzw_horoscope
39,69
34,69
#! usr/bin/env python # -*- coding: utf-8 -*- """ 爬取 星座屋 星座运势 https://www.xzw.com/ """ import re from functools import reduce import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_xzw_horoscope', 'get_today_horoscope'] XZW_BASE_URL_TODAY = "https...
#! usr/bin/env python # -*- coding: utf-8 -*- """ 爬取 星座屋 星座运势 https://www.xzw.com/ """ import re from functools import reduce import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_xzw_horoscope', 'get_today_horoscope'] XZW_BASE_URL_TODAY = "https...
if not name in CONSTELLATION_DICT: print('星座输入有误') return try: const_code = CONSTELLATION_DICT[name] req_url = XZW_BASE_URL_TOMORROW.format(const_code) if is_tomorrow \ else XZW_BASE_URL_TODAY.format(const_code) resp = requests.get(req_url, headers=SPIDER_HE...
''' 获取星座屋(https://www.xzw.com)的星座运势 :param name: 星座名称 :return: ''' if not name in CONSTELLATION_DICT: print('星座输入有误') return try: const_code = CONSTELLATION_DICT[name] req_url = XZW_BASE_URL_TOMORROW.format(const_code) if is_tomorrow \ else XZW_BA...
69
514
454
968
#! usr/bin/env python # -*- coding: utf-8 -*- """ 爬取 星座屋 星座运势 https://www.xzw.com/ """ import re from functools import reduce import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_xzw_horoscope', 'get_today_horoscope'] XZW_BASE_URL_TODAY = "https...
#! usr/bin/env python # -*- coding: utf-8 -*- """ 爬取 星座屋 星座运势 https://www.xzw.com/ """ import re from functools import reduce import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_xzw_horoscope', 'get_today_horoscope'] XZW_BASE_URL_TODAY = "https...
24,050
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/moviebox/maoyan_movie_box.py
16,17
1,70
get_maoyan_movie_box
24,70
17,70
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-30 12:22 Introduction: 猫眼实时票房 地址:https://piaofang.maoyan.com/dashboard 接口地址:https://piaofang.maoyan.com/second-box?beginDate=20190924 """ import requests from datetime import datetime from everyday_wechat.utils.comm...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-30 12:22 Introduction: 猫眼实时票房 地址:https://piaofang.maoyan.com/dashboard 接口地址:https://piaofang.maoyan.com/second-box?beginDate=20190924 """ import requests from datetime import datetime from everyday_wechat.utils.comm...
date_ = date or datetime.now().strftime('%Y%m%d') print('获取 {} 的票房数据...'.format(date_)) # try: url = 'https://piaofang.maoyan.com/second-box?beginDate={}'.format(date_) resp = requests.get(url, headers=SPIDER_HEADERS) # print(resp) if resp.status_code == 200: # print(resp.text) ...
""" 获取特定日期的实时票房日期 https://piaofang.maoyan.com/second-box?beginDate=20190830#指定日期的节假日及万年历信息 :param date: str 日期 格式 yyyyMMdd :param is_expired :rtype str """ date_ = date or datetime.now().strftime('%Y%m%d') print('获取 {} 的票房数据...'.format(date_)) # try: url = 'https://piaofan...
108
275
616
891
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-30 12:22 Introduction: 猫眼实时票房 地址:https://piaofang.maoyan.com/dashboard 接口地址:https://piaofang.maoyan.com/second-box?beginDate=20190924 """ import requests from datetime import datetime from everyday_wechat.utils.comm...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-08-30 12:22 Introduction: 猫眼实时票房 地址:https://piaofang.maoyan.com/dashboard 接口地址:https://piaofang.maoyan.com/second-box?beginDate=20190924 """ import requests from datetime import datetime from everyday_wechat.utils.comm...
24,051
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/onewords/acib.py
15,16
1,36
get_acib_info
20,35
16,35
# coding=utf-8 """ 从词霸中获取每日一句,带英文。 """ import requests from everyday_wechat.utils.common import ( is_json ) __all__ = ['get_acib_info'] def get_acib_info(): FILL_FUNC_BODYget_one_words = get_acib_info
# coding=utf-8 """ 从词霸中获取每日一句,带英文。 """ import requests from everyday_wechat.utils.common import ( is_json ) __all__ = ['get_acib_info'] def get_acib_info(): """ 从词霸中获取每日一句,带英文。 :return:str ,返回每日一句(双语) """ FILL_FUNC_BODYget_one_words = get_acib_info
print('获取格言信息(双语)...') try: resp = requests.get('http://open.iciba.com/dsapi') if resp.status_code == 200 and is_json(resp): content_dict = resp.json() content = content_dict.get('content') note = content_dict.get('note') return '{}{}'.format(conte...
""" 从词霸中获取每日一句,带英文。 :return:str ,返回每日一句(双语) """ print('获取格言信息(双语)...') try: resp = requests.get('http://open.iciba.com/dsapi') if resp.status_code == 200 and is_json(resp): content_dict = resp.json() content = content_dict.get('content') note =...
31
134
160
294
# coding=utf-8 """ 从词霸中获取每日一句,带英文。 """ import requests from everyday_wechat.utils.common import ( is_json ) __all__ = ['get_acib_info'] def get_acib_info(): FILL_FUNC_BODYget_one_words = get_acib_info
# coding=utf-8 """ 从词霸中获取每日一句,带英文。 """ import requests from everyday_wechat.utils.common import ( is_json ) __all__ = ['get_acib_info'] def get_acib_info(): """ 从词霸中获取每日一句,带英文。 :return:str ,返回每日一句(双语) """ FILL_FUNC_BODYget_one_words = get_acib_info
24,052
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/onewords/caihongpi.py
11,12
1,34
get_caihongpi_info
16,28
12,28
# coding=utf-8 """ https://chp.shadiao.app/?from_nmsl 彩虹屁生成器 """ import requests __all__ = ['get_caihongpi_info'] def get_caihongpi_info(): FILL_FUNC_BODYget_one_words = get_caihongpi_info if __name__ == '__main__': ow = get_one_words() print(ow) pass
# coding=utf-8 """ https://chp.shadiao.app/?from_nmsl 彩虹屁生成器 """ import requests __all__ = ['get_caihongpi_info'] def get_caihongpi_info(): """ 彩虹屁生成器 :return: str,彩虹屁 """ FILL_FUNC_BODYget_one_words = get_caihongpi_info if __name__ == '__main__': ow = get_one_words() print(ow) pass
print('获取彩虹屁信息...') try: resp = requests.get('https://chp.shadiao.app/api.php') if resp.status_code == 200: return resp.text print('彩虹屁获取失败。') except requests.exceptions.RequestException as exception: print(exception) # return None # return None
""" 彩虹屁生成器 :return: str,彩虹屁 """ print('获取彩虹屁信息...') try: resp = requests.get('https://chp.shadiao.app/api.php') if resp.status_code == 200: return resp.text print('彩虹屁获取失败。') except requests.exceptions.RequestException as exception: print(exception...
23
159
116
275
# coding=utf-8 """ https://chp.shadiao.app/?from_nmsl 彩虹屁生成器 """ import requests __all__ = ['get_caihongpi_info'] def get_caihongpi_info(): FILL_FUNC_BODYget_one_words = get_caihongpi_info if __name__ == '__main__': ow = get_one_words() print(ow) pass
# coding=utf-8 """ https://chp.shadiao.app/?from_nmsl 彩虹屁生成器 """ import requests __all__ = ['get_caihongpi_info'] def get_caihongpi_info(): """ 彩虹屁生成器 :return: str,彩虹屁 """ FILL_FUNC_BODYget_one_words = get_caihongpi_info if __name__ == '__main__': ow = get_one_words() print(ow) pass
24,053
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/onewords/hitokoto.py
11,12
1,29
get_hitokoto_info
16,28
12,28
# coding=utf-8 """ 获取一言信息<https://hitokoto.cn/> """ import requests __all__ = ['get_hitokoto_info'] def get_hitokoto_info(): FILL_FUNC_BODYget_one_words = get_hitokoto_info
# coding=utf-8 """ 获取一言信息<https://hitokoto.cn/> """ import requests __all__ = ['get_hitokoto_info'] def get_hitokoto_info(): """ 从『一言』获取信息。(官网:https://hitokoto.cn/) :return: str,一言。 """ FILL_FUNC_BODYget_one_words = get_hitokoto_info
print('获取一言...') try: resp = requests.get('https://v1.hitokoto.cn/', params={'encode': 'text'}) if resp.status_code == 200: return resp.text print('一言获取失败。') except requests.exceptions.RequestException as exception: print(exception) # return None # ret...
""" 从『一言』获取信息。(官网:https://hitokoto.cn/) :return: str,一言。 """ print('获取一言...') try: resp = requests.get('https://v1.hitokoto.cn/', params={'encode': 'text'}) if resp.status_code == 200: return resp.text print('一言获取失败。') except requests.exceptions.RequestExc...
25
128
115
243
# coding=utf-8 """ 获取一言信息<https://hitokoto.cn/> """ import requests __all__ = ['get_hitokoto_info'] def get_hitokoto_info(): FILL_FUNC_BODYget_one_words = get_hitokoto_info
# coding=utf-8 """ 获取一言信息<https://hitokoto.cn/> """ import requests __all__ = ['get_hitokoto_info'] def get_hitokoto_info(): """ 从『一言』获取信息。(官网:https://hitokoto.cn/) :return: str,一言。 """ FILL_FUNC_BODYget_one_words = get_hitokoto_info
24,054
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/onewords/juzimi.py
14,15
1,57
get_zsh_info
22,50
15,50
# coding=utf-8 """ 句子迷:(https://www.juzimi.com/) 民国情书:朱生豪先生的情话 && 爱你就像爱生命 Author: ClaireYiu(https://github.com/ClaireYiu) """ import random import requests # from requests_html import HTMLSession def get_zsh_info(): FILL_FUNC_BODYget_one_words = get_zsh_info if __name__ == '__main__': # for _ in range(15): ...
# coding=utf-8 """ 句子迷:(https://www.juzimi.com/) 民国情书:朱生豪先生的情话 && 爱你就像爱生命 Author: ClaireYiu(https://github.com/ClaireYiu) """ import random import requests # from requests_html import HTMLSession def get_zsh_info(): """ 句子迷:(https://www.juzimi.com/) 朱生豪:https://www.juzimi.com/writer/朱生豪 爱你就像爱生命(王小波)...
print('正在获取民国情话...') try: name = [ ['writer/朱生豪', 38, ], ['article/爱你就像爱生命', 22], ['article/25637', 55], ] apdix = random.choice(name) # page 从零开始计数的。 url = 'https://www.juzimi.com/{}?page={}'.format( apdix[0], random.randin...
""" 句子迷:(https://www.juzimi.com/) 朱生豪:https://www.juzimi.com/writer/朱生豪 爱你就像爱生命(王小波):https://www.juzimi.com/article/爱你就像爱生命 三行情书:https://www.juzimi.com/article/25637 :return: str 情话 """ print('正在获取民国情话...') try: name = [ ['writer/朱生豪', 38, ], ['article...
71
292
324
616
# coding=utf-8 """ 句子迷:(https://www.juzimi.com/) 民国情书:朱生豪先生的情话 && 爱你就像爱生命 Author: ClaireYiu(https://github.com/ClaireYiu) """ import random import requests # from requests_html import HTMLSession def get_zsh_info(): FILL_FUNC_BODYget_one_words = get_zsh_info if __name__ == '__main__': # for _ in range(15): ...
# coding=utf-8 """ 句子迷:(https://www.juzimi.com/) 民国情书:朱生豪先生的情话 && 爱你就像爱生命 Author: ClaireYiu(https://github.com/ClaireYiu) """ import random import requests # from requests_html import HTMLSession def get_zsh_info(): """ 句子迷:(https://www.juzimi.com/) 朱生豪:https://www.juzimi.com/writer/朱生豪 爱你就像爱生命(王小波)...
24,055
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/onewords/lovelive.py
10,11
1,28
get_lovelive_info
15,27
11,27
# coding=utf-8 """ 从土味情话中获取每日一句。 """ import requests __all__ = ['get_lovelive_info'] def get_lovelive_info(): FILL_FUNC_BODYget_one_words = get_lovelive_info
# coding=utf-8 """ 从土味情话中获取每日一句。 """ import requests __all__ = ['get_lovelive_info'] def get_lovelive_info(): """ 从土味情话中获取每日一句。 :return: str,土味情话。 """ FILL_FUNC_BODYget_one_words = get_lovelive_info
print('获取土味情话...') try: resp = requests.get('https://api.lovelive.tools/api/SweetNothings') if resp.status_code == 200: return resp.text print('土味情话获取失败。') except requests.exceptions.RequestException as exception: print(exception) # return None return ...
""" 从土味情话中获取每日一句。 :return: str,土味情话。 """ print('获取土味情话...') try: resp = requests.get('https://api.lovelive.tools/api/SweetNothings') if resp.status_code == 200: return resp.text print('土味情话获取失败。') except requests.exceptions.RequestException as exception: ...
22
107
114
221
# coding=utf-8 """ 从土味情话中获取每日一句。 """ import requests __all__ = ['get_lovelive_info'] def get_lovelive_info(): FILL_FUNC_BODYget_one_words = get_lovelive_info
# coding=utf-8 """ 从土味情话中获取每日一句。 """ import requests __all__ = ['get_lovelive_info'] def get_lovelive_info(): """ 从土味情话中获取每日一句。 :return: str,土味情话。 """ FILL_FUNC_BODYget_one_words = get_lovelive_info
24,056
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/onewords/rtjokes.py
11,12
1,40
get_rtjokes_info
16,36
12,36
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#随机获取笑话段子列表 随机获取笑话段子列表 """ import requests __all__ = ['get_rtjokes_info'] def get_rtjokes_info(): FILL_FUNC_BODYget_one_words = get_rtjokes_info if __name__ == '__main__': get_rtjokes_info()
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#随机获取笑话段子列表 随机获取笑话段子列表 """ import requests __all__ = ['get_rtjokes_info'] def get_rtjokes_info(): """ 随机获取笑话段子列表(https://github.com/MZCretin/RollToolsApi#随机获取笑话段子列表) :return: str,笑话。 """ FILL_FUNC_BODYget_one_words = get_rtjokes_info if __na...
print('获取随机笑话...') try: resp = requests.get('https://www.mxnzp.com/api/jokes/list/random') # print(resp.text) if resp.status_code == 200: content_dict = resp.json() if content_dict['code'] == 1: # 每次返回 10 条笑话信息,只取一次 return_text = co...
""" 随机获取笑话段子列表(https://github.com/MZCretin/RollToolsApi#随机获取笑话段子列表) :return: str,笑话。 """ print('获取随机笑话...') try: resp = requests.get('https://www.mxnzp.com/api/jokes/list/random') # print(resp.text) if resp.status_code == 200: content_dict = resp.json() ...
41
180
206
386
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#随机获取笑话段子列表 随机获取笑话段子列表 """ import requests __all__ = ['get_rtjokes_info'] def get_rtjokes_info(): FILL_FUNC_BODYget_one_words = get_rtjokes_info if __name__ == '__main__': get_rtjokes_info()
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#随机获取笑话段子列表 随机获取笑话段子列表 """ import requests __all__ = ['get_rtjokes_info'] def get_rtjokes_info(): """ 随机获取笑话段子列表(https://github.com/MZCretin/RollToolsApi#随机获取笑话段子列表) :return: str,笑话。 """ FILL_FUNC_BODYget_one_words = get_rtjokes_info if __na...
24,057
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/onewords/wufazhuce.py
12,13
1,34
get_wufazhuce_info
17,33
13,33
# coding=utf-8 """ 从「一个」获取每日一言 """ import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_wufazhuce_info'] def get_wufazhuce_info(): FILL_FUNC_BODYget_one_words = get_wufazhuce_info
# coding=utf-8 """ 从「一个」获取每日一言 """ import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_wufazhuce_info'] def get_wufazhuce_info(): """ 获取格言信息(从『一个。one』获取信息 http://wufazhuce.com/) :return: str, 一句格言或者短语。 """ FILL_FUNC_BODYget_one_words =...
print('获取 ONE 信息...') user_url = 'http://wufazhuce.com/' try: resp = requests.get(user_url, headers=SPIDER_HEADERS) if resp.status_code == 200: soup_texts = BeautifulSoup(resp.text, 'lxml') # 『one -个』 中的每日一句 every_msg = soup_texts.find('div', class_='fp-on...
""" 获取格言信息(从『一个。one』获取信息 http://wufazhuce.com/) :return: str, 一句格言或者短语。 """ print('获取 ONE 信息...') user_url = 'http://wufazhuce.com/' try: resp = requests.get(user_url, headers=SPIDER_HEADERS) if resp.status_code == 200: soup_texts = BeautifulSoup(resp.text, 'lxml'...
43
159
196
355
# coding=utf-8 """ 从「一个」获取每日一言 """ import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_wufazhuce_info'] def get_wufazhuce_info(): FILL_FUNC_BODYget_one_words = get_wufazhuce_info
# coding=utf-8 """ 从「一个」获取每日一言 """ import requests from bs4 import BeautifulSoup from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_wufazhuce_info'] def get_wufazhuce_info(): """ 获取格言信息(从『一个。one』获取信息 http://wufazhuce.com/) :return: str, 一句格言或者短语。 """ FILL_FUNC_BODYget_one_words =...
24,058
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/rubbish/atoolbox_rubbish.py
15,16
1,42
get_atoolbox_rubbish
21,42
16,42
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-14 01:02 Introduction: http://www.atoolbox.net/Tool.php?Id=804 """ import requests from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_atoolbox_rubbish'] def get_atoolbox_rubbish(key): FILL_FUN...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-14 01:02 Introduction: http://www.atoolbox.net/Tool.php?Id=804 """ import requests from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_atoolbox_rubbish'] def get_atoolbox_rubbish(key): """ ...
params = {'key': key} resp = requests.get('http://www.atoolbox.net/api/GetRefuseClassification.php', headers=SPIDER_HEADERS, params=params) if resp.status_code == 200: # print(resp.text) content_dict = resp.json() if not content_dict: ...
""" # http://www.atoolbox.net/Tool.php?Id=804 :param key: :return: """ params = {'key': key} resp = requests.get('http://www.atoolbox.net/api/GetRefuseClassification.php', headers=SPIDER_HEADERS, params=params) if resp.status_code == 200: ...
65
180
230
410
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-14 01:02 Introduction: http://www.atoolbox.net/Tool.php?Id=804 """ import requests from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_atoolbox_rubbish'] def get_atoolbox_rubbish(key): FILL_FUN...
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-14 01:02 Introduction: http://www.atoolbox.net/Tool.php?Id=804 """ import requests from everyday_wechat.utils.common import SPIDER_HEADERS __all__ = ['get_atoolbox_rubbish'] def get_atoolbox_rubbish(key): """ ...
24,059
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/weather/rtweather.py
15,16
1,61
get_rttodayweather
22,52
16,52
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#获取特定城市今日天气 获取特定城市今日天气 """ import requests __all__ = ['get_rttodayweather'] # {"code":1,"msg":"数据返回成功","data":{"address":"广西壮族自治区 桂林市 全州县", # "cityCode":"450324","temp":"26℃","weather":"晴","windDirection":"东北","windPower":"≤3级", # "humidity":"58%","reportTim...
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#获取特定城市今日天气 获取特定城市今日天气 """ import requests __all__ = ['get_rttodayweather'] # {"code":1,"msg":"数据返回成功","data":{"address":"广西壮族自治区 桂林市 全州县", # "cityCode":"450324","temp":"26℃","weather":"晴","windDirection":"东北","windPower":"≤3级", # "humidity":"58%","reportTim...
print('获取 {} 的天气...'.format(cityname)) try: # forecast resp = requests.get('https://www.mxnzp.com/api/weather/forecast/{}'.format(cityname)) print(resp.text) if resp.status_code == 200: content_dict = resp.json() if content_dict['code'] == 1: ...
""" 获取特定城市今日天气 https://github.com/MZCretin/RollToolsApi#获取特定城市今日天气 :param cityname:str 传入你需要查询的城市,请尽量传入完整值,否则系统会自行匹配,可能会有误差 :return:str 天气(2019-06-12 星期三 晴 南风 3-4级 高温 22.0℃ 低温 18.0℃ 愿你拥有比阳光明媚的心情) """ print('获取 {} 的天气...'.format(cityname)) try: # forecast resp = requests....
77
388
342
730
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#获取特定城市今日天气 获取特定城市今日天气 """ import requests __all__ = ['get_rttodayweather'] # {"code":1,"msg":"数据返回成功","data":{"address":"广西壮族自治区 桂林市 全州县", # "cityCode":"450324","temp":"26℃","weather":"晴","windDirection":"东北","windPower":"≤3级", # "humidity":"58%","reportTim...
# coding=utf-8 """ https://github.com/MZCretin/RollToolsApi#获取特定城市今日天气 获取特定城市今日天气 """ import requests __all__ = ['get_rttodayweather'] # {"code":1,"msg":"数据返回成功","data":{"address":"广西壮族自治区 桂林市 全州县", # "cityCode":"450324","temp":"26℃","weather":"晴","windDirection":"东北","windPower":"≤3级", # "humidity":"58%","reportTim...
24,060
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/control/weather/sojson.py
84,85
1,141
get_sojson_weather_tomorrow
90,134
85,134
# coding=utf-8 import requests import json import os from datetime import datetime from datetime import timedelta __all__ = ['get_sojson_weather', 'get_sojson_weather_tomorrow'] with open(os.path.join(os.path.dirname(__file__), '_city_sojson.json'), 'r', encoding='utf-8') as f: CITY_CODE_DICT = json.loads(f.read...
# coding=utf-8 import requests import json import os from datetime import datetime from datetime import timedelta __all__ = ['get_sojson_weather', 'get_sojson_weather_tomorrow'] with open(os.path.join(os.path.dirname(__file__), '_city_sojson.json'), 'r', encoding='utf-8') as f: CITY_CODE_DICT = json.loads(f.read...
if not city_name: return None city_code = CITY_CODE_DICT.get(city_name, None) if not city_code: print('没有此城市的消息...') return None print('获取天气信息...') weather_url = 'http://t.weather.sojson.com/api/weather/city/{}'.format(city_code) try: resp = requests.get(url=weat...
""" 获取明日天气信息。网址:https://www.sojson.com/blog/305.html . :param city_name: str,城市名 :return: str ,例如:2019-06-12 星期三 晴 南风 3-4级 高温 22.0℃ 低温 18.0℃ 愿你拥有比阳光明媚的心情 """ if not city_name: return None city_code = CITY_CODE_DICT.get(city_name, None) if not city_code: print('没有此城市的消息.....
88
1,256
609
1,865
# coding=utf-8 import requests import json import os from datetime import datetime from datetime import timedelta __all__ = ['get_sojson_weather', 'get_sojson_weather_tomorrow'] with open(os.path.join(os.path.dirname(__file__), '_city_sojson.json'), 'r', encoding='utf-8') as f: CITY_CODE_DICT = json.loads(f.read...
# coding=utf-8 import requests import json import os from datetime import datetime from datetime import timedelta __all__ = ['get_sojson_weather', 'get_sojson_weather_tomorrow'] with open(os.path.join(os.path.dirname(__file__), '_city_sojson.json'), 'r', encoding='utf-8') as f: CITY_CODE_DICT = json.loads(f.read...
24,062
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/utils/common.py
75,76
1,99
get_constellation_name
81,96
76,96
# coding=utf-8 """ 工具类 """ import re import hashlib import json __all__ = [ 'FILEHELPER_MARK', 'FILEHELPER', 'SPIDER_HEADERS', 'WEEK_DICT', 'BIRTHDAY_COMPILE', 'CONSTELLATION_NAME_LIST', 'CONSTELLATION_DATE_DICT', 'is_json', 'md5_encode', 'get_constellation_name'] FILEHELPER_MARK = ['文件传输助手', 'filehelper'...
# coding=utf-8 """ 工具类 """ import re import hashlib import json __all__ = [ 'FILEHELPER_MARK', 'FILEHELPER', 'SPIDER_HEADERS', 'WEEK_DICT', 'BIRTHDAY_COMPILE', 'CONSTELLATION_NAME_LIST', 'CONSTELLATION_DATE_DICT', 'is_json', 'md5_encode', 'get_constellation_name'] FILEHELPER_MARK = ['文件传输助手', 'filehelper'...
if not date: return date = date.strip() if date in CONSTELLATION_NAME_LIST: return date times = BIRTHDAY_COMPILE.findall(date) if times: month, day = int(times[0][0]), int(times[0][1]) for k, v in CONSTELLATION_DATE_DICT.items(): if k > (month, day): ...
''' 通过日期来返回星座名,或者檢查星座名是否正確。 :param date: 指定日期或者星座名 :return:rtype str ''' if not date: return date = date.strip() if date in CONSTELLATION_NAME_LIST: return date times = BIRTHDAY_COMPILE.findall(date) if times: month, day = int(times[0][0]), int(times[0][1...
37
969
139
1,108
# coding=utf-8 """ 工具类 """ import re import hashlib import json __all__ = [ 'FILEHELPER_MARK', 'FILEHELPER', 'SPIDER_HEADERS', 'WEEK_DICT', 'BIRTHDAY_COMPILE', 'CONSTELLATION_NAME_LIST', 'CONSTELLATION_DATE_DICT', 'is_json', 'md5_encode', 'get_constellation_name'] FILEHELPER_MARK = ['文件传输助手', 'filehelper'...
# coding=utf-8 """ 工具类 """ import re import hashlib import json __all__ = [ 'FILEHELPER_MARK', 'FILEHELPER', 'SPIDER_HEADERS', 'WEEK_DICT', 'BIRTHDAY_COMPILE', 'CONSTELLATION_NAME_LIST', 'CONSTELLATION_DATE_DICT', 'is_json', 'md5_encode', 'get_constellation_name'] FILEHELPER_MARK = ['文件传输助手', 'filehelper'...
24,063
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/utils/config.py
24,25
1,70
get_yaml
29,41
25,41
# coding=utf-8 """ 用于管理缓存的配置数据 使用前必须先调用 init() 。 """ import os import copy as mycopy import yaml __all__ = ['set', 'get', 'copy', 'update', '_print'] # def init(): # """ # 将 yaml 里的配置文件导入到 config.py 中 # :return: bool ,true 表示数据导入成功。 # """ # global opts # opts = get_yaml() # if opts: # ...
# coding=utf-8 """ 用于管理缓存的配置数据 使用前必须先调用 init() 。 """ import os import copy as mycopy import yaml __all__ = ['set', 'get', 'copy', 'update', '_print'] # def init(): # """ # 将 yaml 里的配置文件导入到 config.py 中 # :return: bool ,true 表示数据导入成功。 # """ # global opts # opts = get_yaml() # if opts: # ...
path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '_config.yaml') try: with open(path, 'r', encoding='utf-8') as file: config = yaml.safe_load(file) # config = yaml.load(file, Loader=yaml.Loader) return config except Exception as exception: prin...
""" 解析 yaml :return: s 字典 """ path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '_config.yaml') try: with open(path, 'r', encoding='utf-8') as file: config = yaml.safe_load(file) # config = yaml.load(file, Loader=yaml.Loader) return config ...
31
356
144
500
# coding=utf-8 """ 用于管理缓存的配置数据 使用前必须先调用 init() 。 """ import os import copy as mycopy import yaml __all__ = ['set', 'get', 'copy', 'update', '_print'] # def init(): # """ # 将 yaml 里的配置文件导入到 config.py 中 # :return: bool ,true 表示数据导入成功。 # """ # global opts # opts = get_yaml() # if opts: # ...
# coding=utf-8 """ 用于管理缓存的配置数据 使用前必须先调用 init() 。 """ import os import copy as mycopy import yaml __all__ = ['set', 'get', 'copy', 'update', '_print'] # def init(): # """ # 将 yaml 里的配置文件导入到 config.py 中 # :return: bool ,true 表示数据导入成功。 # """ # global opts # opts = get_yaml() # if opts: # ...
24,064
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/everyday_wechat/utils/friend_helper.py
23,24
1,68
handle_friend
25,68
24,68
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-12 23:07 Introduction: 处理好友消息内容 """ import time import random import itchat from everyday_wechat.utils import config from everyday_wechat.utils.data_collection import ( get_bot_info, ) from everyday_wechat.utils....
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-12 23:07 Introduction: 处理好友消息内容 """ import time import random import itchat from everyday_wechat.utils import config from everyday_wechat.utils.data_collection import ( get_bot_info, ) from everyday_wechat.utils....
try: # 自己通过手机微信发送给别人的消息(文件传输助手除外)不作处理。 if msg['FromUserName'] == config.get('wechat_uuid') and msg['ToUserName'] != FILEHELPER: return conf = config.get('auto_reply_info') if not conf.get('is_auto_reply'): return # 获取发送者的用户id uuid = FILEHELPE...
""" 处理好友信息 """ try: # 自己通过手机微信发送给别人的消息(文件传输助手除外)不作处理。 if msg['FromUserName'] == config.get('wechat_uuid') and msg['ToUserName'] != FILEHELPER: return conf = config.get('auto_reply_info') if not conf.get('is_auto_reply'): return # 获取发送者的用户id ...
127
170
655
825
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-12 23:07 Introduction: 处理好友消息内容 """ import time import random import itchat from everyday_wechat.utils import config from everyday_wechat.utils.data_collection import ( get_bot_info, ) from everyday_wechat.utils....
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-12 23:07 Introduction: 处理好友消息内容 """ import time import random import itchat from everyday_wechat.utils import config from everyday_wechat.utils.data_collection import ( get_bot_info, ) from everyday_wechat.utils....
24,067
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat
/home/hieuvd/dung_repo/raw/stars_01/sfyc23_EverydayWechat/EverydayWechat/run.py
23,24
1,71
run
25,69
24,69
# coding=utf-8 """ 程序运行入口 """ import sys import re from datetime import datetime try: from everyday_wechat import __version__ print('EverydayWechat 程序版本号:{}'.format(__version__)) _date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print('当前时间:{}'.format(_date)) except Exception as exception: pri...
# coding=utf-8 """ 程序运行入口 """ import sys import re from datetime import datetime try: from everyday_wechat import __version__ print('EverydayWechat 程序版本号:{}'.format(__version__)) _date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print('当前时间:{}'.format(_date)) except Exception as exception: pri...
# 判断当前环境是否为 python 3 if sys.version_info[0] == 2: print('此项目不支持 Python 2 版本!') return # 检查依赖库是否都已经安装上 try: import itchat import apscheduler import requests from bs4 import BeautifulSoup if itchat.__version__ != '1.3.10': print('当前 itc...
""" 主程序入口""" # 判断当前环境是否为 python 3 if sys.version_info[0] == 2: print('此项目不支持 Python 2 版本!') return # 检查依赖库是否都已经安装上 try: import itchat import apscheduler import requests from bs4 import BeautifulSoup if itchat.__version__ != '1.3.10': ...
104
205
495
700
# coding=utf-8 """ 程序运行入口 """ import sys import re from datetime import datetime try: from everyday_wechat import __version__ print('EverydayWechat 程序版本号:{}'.format(__version__)) _date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print('当前时间:{}'.format(_date)) except Exception as exception: pri...
# coding=utf-8 """ 程序运行入口 """ import sys import re from datetime import datetime try: from everyday_wechat import __version__ print('EverydayWechat 程序版本号:{}'.format(__version__)) _date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print('当前时间:{}'.format(_date)) except Exception as exception: pri...
24,194
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret.py
8,9
1,22
run
9,20
9,20
#!/usr/bin/env python3 import asyncio import sys from maigret.maigret import main def run(): FILL_FUNC_BODYif __name__ == "__main__": run()
#!/usr/bin/env python3 import asyncio import sys from maigret.maigret import main def run(): FILL_FUNC_BODYif __name__ == "__main__": run()
try: if sys.version_info.minor >= 10: asyncio.run(main()) else: loop = asyncio.get_event_loop() loop.run_until_complete(main()) except KeyboardInterrupt: print('Maigret is interrupted.') sys.exit(1)
try: if sys.version_info.minor >= 10: asyncio.run(main()) else: loop = asyncio.get_event_loop() loop.run_until_complete(main()) except KeyboardInterrupt: print('Maigret is interrupted.') sys.exit(1)
17
58
96
154
#!/usr/bin/env python3 import asyncio import sys from maigret.maigret import main def run(): FILL_FUNC_BODYif __name__ == "__main__": run()
#!/usr/bin/env python3 import asyncio import sys from maigret.maigret import main def run(): FILL_FUNC_BODYif __name__ == "__main__": run()
24,195
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/activation.py
43,44
1,61
import_aiohttp_cookies
44,61
44,61
from http.cookiejar import MozillaCookieJar from http.cookies import Morsel from aiohttp import CookieJar class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(s...
from http.cookiejar import MozillaCookieJar from http.cookies import Morsel from aiohttp import CookieJar class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(s...
cookies_obj = MozillaCookieJar(cookiestxt_filename) cookies_obj.load(ignore_discard=True, ignore_expires=True) cookies = CookieJar() cookies_list = [] for domain in cookies_obj._cookies.values(): for key, cookie in list(domain.values())[0].items(): c = Morsel() c.se...
cookies_obj = MozillaCookieJar(cookiestxt_filename) cookies_obj.load(ignore_discard=True, ignore_expires=True) cookies = CookieJar() cookies_list = [] for domain in cookies_obj._cookies.values(): for key, cookie in list(domain.values())[0].items(): c = Morsel() c.se...
37
402
184
586
from http.cookiejar import MozillaCookieJar from http.cookies import Morsel from aiohttp import CookieJar class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(s...
from http.cookiejar import MozillaCookieJar from http.cookies import Morsel from aiohttp import CookieJar class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(s...
24,196
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/activation.py
31,33
7,43
spotify
ParsingActivator
33,43
33,43
class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(site.activation["url"], headers=headers) logger.info(r) j = r.json() guest_token = j[s...
class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(site.activation["url"], headers=headers) logger.info(r) j = r.json() guest_token = j[s...
headers = dict(site.headers) if "Authorization" in headers: del headers["Authorization"] import requests r = requests.get(site.activation["url"]) bearer_token = r.json()["accessToken"] site.headers["authorization"] = f"Bearer {bearer_token}"
headers = dict(site.headers) if "Authorization" in headers: del headers["Authorization"] import requests r = requests.get(site.activation["url"]) bearer_token = r.json()["accessToken"] site.headers["authorization"] = f"Bearer {bearer_token}"
21
262
96
358
from http.cookiejar import MozillaCookieJar from http.cookies import Morsel from aiohttp import CookieJar class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(s...
from http.cookiejar import MozillaCookieJar from http.cookies import Morsel from aiohttp import CookieJar class ParsingActivator: @staticmethod def twitter(site, logger, cookies={}): headers = dict(site.headers) del headers["x-guest-token"] import requests r = requests.post(s...
24,198
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/checking.py
170,171
158,188
check
AiodnsDomainResolver
171,188
171,188
class AiodnsDomainResolver(CheckerBase): if sys.platform == 'win32': # Temporary workaround for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) def __init__(self, *args, **kwargs): loop = asyncio.get_event_loop() self.logger = kwargs.get('logger', Mock()...
class AiodnsDomainResolver(CheckerBase): if sys.platform == 'win32': # Temporary workaround for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) def __init__(self, *args, **kwargs): loop = asyncio.get_event_loop() self.logger = kwargs.get('logger', Mock()...
status = 404 error = None text = '' try: res = await future text = str(res[0].host) status = 200 except aiodns.error.DNSError: pass except Exception as e: self.logger.error(e, exc_info=True) error = ...
status = 404 error = None text = '' try: res = await future text = str(res[0].host) status = 200 except aiodns.error.DNSError: pass except Exception as e: self.logger.error(e, exc_info=True) error = ...
39
199
131
330
import asyncio import logging try: from mock import Mock except ImportError: from unittest.mock import Mock import ast import re import ssl import sys import tqdm import random from typing import Tuple, Optional, Dict, List from urllib.parse import quote import aiodns import tqdm.asyncio from python_socks im...
import asyncio import logging try: from mock import Mock except ImportError: from unittest.mock import Mock import ast import re import ssl import sys import tqdm import random from typing import Tuple, Optional, Dict, List from urllib.parse import quote import aiodns import tqdm.asyncio from python_socks im...
24,199
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/checking.py
195,196
188,204
check
CheckerMock
196,199
196,199
class CheckerMock: def __init__(self, *args, **kwargs): pass def prepare(self, url, headers=None, allow_redirects=True, timeout=0, method='get'): return None async def check(self, future) -> Tuple[str, int, Optional[CheckError]]: FILL_FUNC_BODY async def close(self): return # ...
class CheckerMock: def __init__(self, *args, **kwargs): pass def prepare(self, url, headers=None, allow_redirects=True, timeout=0, method='get'): return None async def check(self, future) -> Tuple[str, int, Optional[CheckError]]: FILL_FUNC_BODY async def close(self): return # ...
await asyncio.sleep(0) return '', 0, None
await asyncio.sleep(0) return '', 0, None
6
116
22
138
import asyncio import logging try: from mock import Mock except ImportError: from unittest.mock import Mock import ast import re import ssl import sys import tqdm import random from typing import Tuple, Optional, Dict, List from urllib.parse import quote import aiodns import tqdm.asyncio from python_socks im...
import asyncio import logging try: from mock import Mock except ImportError: from unittest.mock import Mock import ast import re import ssl import sys import tqdm import random from typing import Tuple, Optional, Dict, List from urllib.parse import quote import aiodns import tqdm.asyncio from python_socks im...
24,200
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/checking.py
93,94
59,142
check
SimpleAiohttpChecker
94,142
94,142
class SimpleAiohttpChecker(CheckerBase): def __init__(self, *args, **kwargs): proxy = kwargs.get('proxy') cookie_jar = kwargs.get('cookie_jar') self.logger = kwargs.get('logger', Mock()) # moved here to speed up the launch of Maigret from aiohttp_socks import ProxyConnector ...
class SimpleAiohttpChecker(CheckerBase): def __init__(self, *args, **kwargs): proxy = kwargs.get('proxy') cookie_jar = kwargs.get('cookie_jar') self.logger = kwargs.get('logger', Mock()) # moved here to speed up the launch of Maigret from aiohttp_socks import ProxyConnector ...
html_text = None status_code = 0 error: Optional[CheckError] = CheckError("Unknown") try: response = await future status_code = response.status response_content = await response.content.read() charset = response.charset or "utf-8" ...
html_text = None status_code = 0 error: Optional[CheckError] = CheckError("Unknown") try: response = await future status_code = response.status response_content = await response.content.read() charset = response.charset or "utf-8" ...
136
347
493
840
import asyncio import logging try: from mock import Mock except ImportError: from unittest.mock import Mock import ast import re import ssl import sys import tqdm import random from typing import Tuple, Optional, Dict, List from urllib.parse import quote import aiodns import tqdm.asyncio from python_socks im...
import asyncio import logging try: from mock import Mock except ImportError: from unittest.mock import Mock import ast import re import ssl import sys import tqdm import random from typing import Tuple, Optional, Dict, List from urllib.parse import quote import aiodns import tqdm.asyncio from python_socks im...
24,201
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/errors.py
115,116
1,138
extract_and_group
116,138
116,138
from typing import Dict, List, Any from .result import QueryResult from .types import QueryResultWrapper # error got as a result of completed search query class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc de...
from typing import Dict, List, Any from .result import QueryResult from .types import QueryResultWrapper # error got as a result of completed search query class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc de...
errors_counts: Dict[str, int] = {} for r in search_res.values(): if r and isinstance(r, dict) and r.get('status'): if not isinstance(r['status'], QueryResult): continue err = r['status'].error if not err: continue errors_co...
errors_counts: Dict[str, int] = {} for r in search_res.values(): if r and isinstance(r, dict) and r.get('status'): if not isinstance(r['status'], QueryResult): continue err = r['status'].error if not err: continue errors_co...
63
1,111
227
1,338
from typing import Dict, List, Any from .result import QueryResult from .types import QueryResultWrapper # error got as a result of completed search query class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc de...
from typing import Dict, List, Any from .result import QueryResult from .types import QueryResultWrapper # error got as a result of completed search query class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc de...
24,202
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/errors.py
22,24
8,31
type
CheckError
24,26
24,26
class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc def __str__(self): if not self._desc: return f'{self._type} error' return f'{self._type} error: {self._desc}' @property de...
class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc def __str__(self): if not self._desc: return f'{self._type} error' return f'{self._type} error: {self._desc}' @property de...
return self._type
return self._type
2
136
9
145
from typing import Dict, List, Any from .result import QueryResult from .types import QueryResultWrapper # error got as a result of completed search query class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc de...
from typing import Dict, List, Any from .result import QueryResult from .types import QueryResultWrapper # error got as a result of completed search query class CheckError: _type = 'Unknown' _desc = '' def __init__(self, typename, desc=''): self._type = typename self._desc = desc de...
24,204
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/notify.py
61,62
14,113
update
QueryNotify
75,80
62,80
class QueryNotify: """Query Notify Object. Base class that describes methods available to notify the results of a query. It is intended that other classes inherit from this base class and override the methods to implement specific functionality. """ def __init__(self, result=None): ...
class QueryNotify: """Query Notify Object. Base class that describes methods available to notify the results of a query. It is intended that other classes inherit from this base class and override the methods to implement specific functionality. """ def __init__(self, result=None): ...
self.result = result return
"""Notify Update. Notify method for query result. This method will typically be overridden by higher level classes that will inherit from it. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing ...
4
596
18
614
"""Sherlock Notify Module This module defines the objects for notifying the caller about the results of queries. """ import sys from colorama import Fore, Style, init from .result import QueryStatus from .utils import get_dict_ascii_tree class QueryNotify: """Query Notify Object. Base class that describes...
"""Sherlock Notify Module This module defines the objects for notifying the caller about the results of queries. """ import sys from colorama import Fore, Style, init from .result import QueryStatus from .utils import get_dict_ascii_tree class QueryNotify: """Query Notify Object. Base class that describes...
24,205
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/notify.py
222,223
113,306
update
QueryNotifyPrint
235,294
223,294
class QueryNotifyPrint(QueryNotify): """Query Notify Print Object. Query notify class that prints results. """ def __init__( self, result=None, verbose=False, print_found_only=False, skip_check_errors=False, color=True, ): """Create Query Not...
class QueryNotifyPrint(QueryNotify): """Query Notify Print Object. Query notify class that prints results. """ def __init__( self, result=None, verbose=False, print_found_only=False, skip_check_errors=False, color=True, ): """Create Query Not...
notify = None self.result = result ids_data_text = "" if self.result.ids_data: ids_data_text = get_dict_ascii_tree(self.result.ids_data.items(), " ") # Output to the terminal is desired. if result.status == QueryStatus.CLAIMED: color = Fore.BLUE ...
"""Notify Update. Will print the query result to the standard output. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing results for this query. Return Value: ...
142
1,020
590
1,610
"""Sherlock Notify Module This module defines the objects for notifying the caller about the results of queries. """ import sys from colorama import Fore, Style, init from .result import QueryStatus from .utils import get_dict_ascii_tree class QueryNotify: """Query Notify Object. Base class that describes...
"""Sherlock Notify Module This module defines the objects for notifying the caller about the results of queries. """ import sys from colorama import Fore, Style, init from .result import QueryStatus from .utils import get_dict_ascii_tree class QueryNotify: """Query Notify Object. Base class that describes...
24,206
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/result.py
89,90
31,118
json
QueryResult
90,99
90,99
class QueryResult: """Query Result Object. Describes result of query about a given username. """ def __init__( self, username, site_name, site_url_user, status, ids_data=None, query_time=None, context=None, error=None, tag...
class QueryResult: """Query Result Object. Describes result of query about a given username. """ def __init__( self, username, site_name, site_url_user, status, ids_data=None, query_time=None, context=None, error=None, tag...
return { "username": self.username, "site_name": self.site_name, "url": self.site_url_user, "status": str(self.status), "ids": self.ids_data or {}, "tags": self.tags, }
return { "username": self.username, "site_name": self.site_name, "url": self.site_url_user, "status": str(self.status), "ids": self.ids_data or {}, "tags": self.tags, }
17
602
84
686
"""Maigret Result Module This module defines various objects for recording the results of queries. """ from enum import Enum class QueryStatus(Enum): """Query Status Enumeration. Describes status of query about a given username. """ CLAIMED = "Claimed" # Username Detected AVAILABLE = "Availabl...
"""Maigret Result Module This module defines various objects for recording the results of queries. """ from enum import Enum class QueryStatus(Enum): """Query Status Enumeration. Describes status of query about a given username. """ CLAIMED = "Claimed" # Username Detected AVAILABLE = "Availabl...
24,207
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/settings.py
53,54
13,86
load
Settings
54,83
54,83
class Settings: # main maigret setting retries_count: int sites_db_path: str timeout: int max_connections: int recursive_search: bool info_extracting: bool cookie_jar_file: str ignore_ids_list: List reports_path: str proxy_url: str tor_proxy_url: str i2p_proxy_url: st...
class Settings: # main maigret setting retries_count: int sites_db_path: str timeout: int max_connections: int recursive_search: bool info_extracting: bool cookie_jar_file: str ignore_ids_list: List reports_path: str proxy_url: str tor_proxy_url: str i2p_proxy_url: st...
was_inited = False if not paths: paths = SETTINGS_FILES_PATHS for filename in paths: data = {} try: with open(filename, "r", encoding="utf-8") as file: data = json.load(file) except FileNotFoundError: ...
was_inited = False if not paths: paths = SETTINGS_FILES_PATHS for filename in paths: data = {} try: with open(filename, "r", encoding="utf-8") as file: data = json.load(file) except FileNotFoundError: ...
73
334
234
568
import os import os.path as path import json from typing import List SETTINGS_FILES_PATHS = [ path.join(path.dirname(path.realpath(__file__)), "resources/settings.json"), '~/.maigret/settings.json', path.join(os.getcwd(), 'settings.json'), ] class Settings: # main maigret setting retries_count: i...
import os import os.path as path import json from typing import List SETTINGS_FILES_PATHS = [ path.join(path.dirname(path.realpath(__file__)), "resources/settings.json"), '~/.maigret/settings.json', path.join(os.getcwd(), 'settings.json'), ] class Settings: # main maigret setting retries_count: i...
24,209
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/sites.py
18,20
11,23
json
MaigretEngine
20,23
20,23
class MaigretEngine: site: Dict[str, Any] = {} def __init__(self, name, data): self.name = name self.__dict__.update(data) @property def json(self): FILL_FUNC_BODY
class MaigretEngine: site: Dict[str, Any] = {} def __init__(self, name, data): self.name = name self.__dict__.update(data) @property def json(self): FILL_FUNC_BODY
return self.__dict__
return self.__dict__
2
73
12
85
# ****************************** -*- """Maigret Sites Information""" import copy import json import sys from typing import Optional, List, Dict, Any, Tuple from .utils import CaseConverter, URLMatcher, is_country_tag class MaigretEngine: site: Dict[str, Any] = {} def __init__(self, name, data): self...
# ****************************** -*- """Maigret Sites Information""" import copy import json import sys from typing import Optional, List, Dict, Any, Tuple from .utils import CaseConverter, URLMatcher, is_country_tag class MaigretEngine: site: Dict[str, Any] = {} def __init__(self, name, data): self...
24,210
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/sites.py
95,96
23,212
detect_username
MaigretSite
96,103
96,103
class MaigretSite: NOT_SERIALIZABLE_FIELDS = [ "name", "engineData", "requestFuture", "detectedEngine", "engineObj", "stats", "urlRegexp", ] username_claimed = "" username_unclaimed = "" url_subpath = "" url_main = "" url = "" disa...
class MaigretSite: NOT_SERIALIZABLE_FIELDS = [ "name", "engineData", "requestFuture", "detectedEngine", "engineObj", "stats", "urlRegexp", ] username_claimed = "" username_unclaimed = "" url_subpath = "" url_main = "" url = "" disa...
if self.url_regexp: match_groups = self.url_regexp.match(url) if match_groups: return match_groups.groups()[-1].rstrip("/") return None
if self.url_regexp: match_groups = self.url_regexp.match(url) if match_groups: return match_groups.groups()[-1].rstrip("/") return None
11
1,667
63
1,730
# ****************************** -*- """Maigret Sites Information""" import copy import json import sys from typing import Optional, List, Dict, Any, Tuple from .utils import CaseConverter, URLMatcher, is_country_tag class MaigretEngine: site: Dict[str, Any] = {} def __init__(self, name, data): self...
# ****************************** -*- """Maigret Sites Information""" import copy import json import sys from typing import Optional, List, Dict, Any, Tuple from .utils import CaseConverter, URLMatcher, is_country_tag class MaigretEngine: site: Dict[str, Any] = {} def __init__(self, name, data): self...
24,211
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/utils.py
109,110
1,122
get_match_ratio
110,122
110,122
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
def get_match_inner(s: str): return round( max( [ difflib.SequenceMatcher(a=s.lower(), b=s2.lower()).ratio() for s2 in base_strs ] ), 2, ) return get_match_inner
def get_match_inner(s: str): return round( max( [ difflib.SequenceMatcher(a=s.lower(), b=s2.lower()).ratio() for s2 in base_strs ] ), 2, ) return get_match_inner
19
1,256
93
1,349
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
24,212
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/utils.py
19,21
14,32
snake_to_camel
CaseConverter
21,25
21,25
class CaseConverter: @staticmethod def camel_to_snake(camelcased_string: str) -> str: return re.sub(r"(?<!^)(?=[A-Z])", "_", camelcased_string).lower() @staticmethod def snake_to_camel(snakecased_string: str) -> str: FILL_FUNC_BODY @staticmethod def snake_to_title(snakecased_string: str)...
class CaseConverter: @staticmethod def camel_to_snake(camelcased_string: str) -> str: return re.sub(r"(?<!^)(?=[A-Z])", "_", camelcased_string).lower() @staticmethod def snake_to_camel(snakecased_string: str) -> str: FILL_FUNC_BODY @staticmethod def snake_to_title(snakecased_string: str)...
formatted = "".join(word.title() for word in snakecased_string.split("_")) result = formatted[0].lower() + formatted[1:] return result
formatted = "".join(word.title() for word in snakecased_string.split("_")) result = formatted[0].lower() + formatted[1:] return result
14
174
50
224
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
24,213
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/maigret/utils.py
57,59
44,72
make_profile_url_regexp
URLMatcher
59,72
59,72
class URLMatcher: _HTTP_URL_RE_STR = "^https?://(www.|m.)?(.+)$" HTTP_URL_RE = re.compile(_HTTP_URL_RE_STR) UNSAFE_SYMBOLS = ".?" @classmethod def extract_main_part(self, url: str) -> str: match = self.HTTP_URL_RE.search(url) if match and match.group(2): return match.gro...
class URLMatcher: _HTTP_URL_RE_STR = "^https?://(www.|m.)?(.+)$" HTTP_URL_RE = re.compile(_HTTP_URL_RE_STR) UNSAFE_SYMBOLS = ".?" @classmethod def extract_main_part(self, url: str) -> str: match = self.HTTP_URL_RE.search(url) if match and match.group(2): return match.gro...
url_main_part = self.extract_main_part(url) for c in self.UNSAFE_SYMBOLS: url_main_part = url_main_part.replace(c, f"\\{c}") prepared_username_regexp = (username_regexp or ".+?").lstrip('^').rstrip('$') url_regexp = url_main_part.replace( "{username}", f"({prepar...
url_main_part = self.extract_main_part(url) for c in self.UNSAFE_SYMBOLS: url_main_part = url_main_part.replace(c, f"\\{c}") prepared_username_regexp = (username_regexp or ".+?").lstrip('^').rstrip('$') url_regexp = url_main_part.replace( "{username}", f"({prepar...
29
181
190
371
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
# coding: utf8 import ast import difflib import re import random from typing import Any DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", ] class CaseConverter: @staticmethod def camel_to_snake(camelcased_string...
24,214
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/utils/add_tags.py
9,10
1,64
update_tags
10,33
10,33
#!/usr/bin/env python3 import random from argparse import ArgumentParser, RawDescriptionHelpFormatter from maigret.maigret import MaigretDatabase from maigret.submit import Submitter def update_tags(site): FILL_FUNC_BODYif __name__ == '__main__': parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatte...
#!/usr/bin/env python3 import random from argparse import ArgumentParser, RawDescriptionHelpFormatter from maigret.maigret import MaigretDatabase from maigret.submit import Submitter def update_tags(site): FILL_FUNC_BODYif __name__ == '__main__': parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatte...
tags = [] if not site.tags: print(f'Site {site.name} doesn\'t have tags') else: tags = site.tags print(f'Site {site.name} tags: ' + ', '.join(tags)) print(f'URL: {site.url_main}') new_tags = set(input('Enter new tags: ').split(', ')) if "disabled" in new_tags: n...
tags = [] if not site.tags: print(f'Site {site.name} doesn\'t have tags') else: tags = site.tags print(f'Site {site.name} tags: ' + ', '.join(tags)) print(f'URL: {site.url_main}') new_tags = set(input('Enter new tags: ').split(', ')) if "disabled" in new_tags: n...
64
353
254
607
#!/usr/bin/env python3 import random from argparse import ArgumentParser, RawDescriptionHelpFormatter from maigret.maigret import MaigretDatabase from maigret.submit import Submitter def update_tags(site): FILL_FUNC_BODYif __name__ == '__main__': parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatte...
#!/usr/bin/env python3 import random from argparse import ArgumentParser, RawDescriptionHelpFormatter from maigret.maigret import MaigretDatabase from maigret.submit import Submitter def update_tags(site): FILL_FUNC_BODYif __name__ == '__main__': parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatte...
24,215
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/utils/sites_diff.py
26,27
1,37
get_match_ratio
27,33
27,33
import sys import difflib import requests a = requests.get(sys.argv[1]).text b = requests.get(sys.argv[2]).text tokens_a = set(a.split('"')) tokens_b = set(b.split('"')) a_minus_b = tokens_a.difference(tokens_b) b_minus_a = tokens_b.difference(tokens_a) print(a_minus_b) print(b_minus_a) print(len(a_minus_b)) pri...
import sys import difflib import requests a = requests.get(sys.argv[1]).text b = requests.get(sys.argv[2]).text tokens_a = set(a.split('"')) tokens_b = set(b.split('"')) a_minus_b = tokens_a.difference(tokens_b) b_minus_a = tokens_b.difference(tokens_a) print(a_minus_b) print(b_minus_a) print(len(a_minus_b)) pri...
return round(max([ difflib.SequenceMatcher(a=x.lower(), b=y).ratio() for y in desired_strings ]), 2)
return round(max([ difflib.SequenceMatcher(a=x.lower(), b=y).ratio() for y in desired_strings ]), 2)
10
299
52
351
import sys import difflib import requests a = requests.get(sys.argv[1]).text b = requests.get(sys.argv[2]).text tokens_a = set(a.split('"')) tokens_b = set(b.split('"')) a_minus_b = tokens_a.difference(tokens_b) b_minus_a = tokens_b.difference(tokens_a) print(a_minus_b) print(b_minus_a) print(len(a_minus_b)) pri...
import sys import difflib import requests a = requests.get(sys.argv[1]).text b = requests.get(sys.argv[2]).text tokens_a = set(a.split('"')) tokens_b = set(b.split('"')) a_minus_b = tokens_a.difference(tokens_b) b_minus_a = tokens_b.difference(tokens_a) print(a_minus_b) print(b_minus_a) print(len(a_minus_b)) pri...
24,216
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/utils/update_site_data.py
59,60
1,148
get_step_rank
60,70
60,70
#!/usr/bin/env python3 """Maigret: Supported Site Listing with Alexa ranking and country tags This module generates the listing of supported sites in file `SITES.md` and pretty prints file with sites data. """ import json import sys import requests import logging import threading import xml.etree.ElementTree as ET from...
#!/usr/bin/env python3 """Maigret: Supported Site Listing with Alexa ranking and country tags This module generates the listing of supported sites in file `SITES.md` and pretty prints file with sites data. """ import json import sys import requests import logging import threading import xml.etree.ElementTree as ET from...
def get_readable_rank(r): return RANKS[str(r)] valid_step_ranks = sorted(map(int, RANKS.keys())) if rank == 0 or rank == sys.maxsize: return get_readable_rank(valid_step_ranks[-1]) else: return get_readable_rank(list(filter(lambda x: x >= rank, valid_step_ranks))[0])
def get_readable_rank(r): return RANKS[str(r)] valid_step_ranks = sorted(map(int, RANKS.keys())) if rank == 0 or rank == sys.maxsize: return get_readable_rank(valid_step_ranks[-1]) else: return get_readable_rank(list(filter(lambda x: x >= rank, valid_step_ranks))[0])
26
1,620
125
1,745
#!/usr/bin/env python3 """Maigret: Supported Site Listing with Alexa ranking and country tags This module generates the listing of supported sites in file `SITES.md` and pretty prints file with sites data. """ import json import sys import requests import logging import threading import xml.etree.ElementTree as ET from...
#!/usr/bin/env python3 """Maigret: Supported Site Listing with Alexa ranking and country tags This module generates the listing of supported sites in file `SITES.md` and pretty prints file with sites data. """ import json import sys import requests import logging import threading import xml.etree.ElementTree as ET from...
24,217
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret
/home/hieuvd/dung_repo/raw/stars_01/soxoj_maigret/maigret/wizard.py
11,12
1,58
main
12,56
12,56
import asyncio import logging import maigret TOP_SITES_COUNT = 300 TIMEOUT = 10 MAX_CONNECTIONS = 50 def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
import asyncio import logging import maigret TOP_SITES_COUNT = 300 TIMEOUT = 10 MAX_CONNECTIONS = 50 def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
logger = logging.getLogger('maigret') logger.setLevel(logging.WARNING) loop = asyncio.get_event_loop() db = maigret.MaigretDatabase().load_from_file('./maigret/resources/data.json') username = input('Enter username to search: ') sites_count = int(input( f'Select the number of sites to ...
logger = logging.getLogger('maigret') logger.setLevel(logging.WARNING) loop = asyncio.get_event_loop() db = maigret.MaigretDatabase().load_from_file('./maigret/resources/data.json') username = input('Enter username to search: ') sites_count = int(input( f'Select the number of sites to ...
138
73
537
610
import asyncio import logging import maigret TOP_SITES_COUNT = 300 TIMEOUT = 10 MAX_CONNECTIONS = 50 def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
import asyncio import logging import maigret TOP_SITES_COUNT = 300 TIMEOUT = 10 MAX_CONNECTIONS = 50 def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
24,728
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle/sshuttle/linux.py
13,14
1,52
ipt_chain_exists
14,30
14,30
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s' % e) def ipt_chain_exists(family, table, name): FILL_FUNC_BODYdef ipt(family, table, *args)...
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s' % e) def ipt_chain_exists(family, table, name): FILL_FUNC_BODYdef ipt(family, table, *args)...
if family == socket.AF_INET6: cmd = 'ip6tables' elif family == socket.AF_INET: cmd = 'iptables' else: raise Exception('Unsupported family "%s"' % family_to_string(family)) argv = [cmd, '-w', '-t', table, '-nL'] try: output = ssubprocess.check_output(argv, env=get_env(...
if family == socket.AF_INET6: cmd = 'ip6tables' elif family == socket.AF_INET: cmd = 'iptables' else: raise Exception('Unsupported family "%s"' % family_to_string(family)) argv = [cmd, '-w', '-t', table, '-nL'] try: output = ssubprocess.check_output(argv, env=get_env(...
56
419
204
623
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s' % e) def ipt_chain_exists(family, table, name): FILL_FUNC_BODYdef ipt(family, table, *args)...
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s' % e) def ipt_chain_exists(family, table, name): FILL_FUNC_BODYdef ipt(family, table, *args)...
24,730
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle/sshuttle/methods/ipfw.py
158,160
115,227
setup_firewall
Method
160,210
160,210
class Method(BaseMethod): def get_supported_features(self): result = super(Method, self).get_supported_features() result.ipv6 = False result.udp = False # NOTE: Almost there, kernel patch needed result.dns = True return result def get_tcp_dstip(self, sock): ret...
class Method(BaseMethod): def get_supported_features(self): result = super(Method, self).get_supported_features() result.ipv6 = False result.udp = False # NOTE: Almost there, kernel patch needed result.dns = True return result def get_tcp_dstip(self, sock): ret...
# IPv6 not supported if family not in [socket.AF_INET]: raise Exception( 'Address family "%s" unsupported by ipfw method_name' % family_to_string(family)) # XXX: Any risk from this? ipfw_noexit('delete', '1') while _changedctls: ...
# IPv6 not supported if family not in [socket.AF_INET]: raise Exception( 'Address family "%s" unsupported by ipfw method_name' % family_to_string(family)) # XXX: Any risk from this? ipfw_noexit('delete', '1') while _changedctls: ...
162
802
655
1,457
import os import subprocess as ssubprocess from sshuttle.methods import BaseMethod from sshuttle.helpers import log, debug1, debug2, debug3, \ Fatal, family_to_string, get_env, which import socket IP_BINDANY = 24 IP_RECVDSTADDR = 7 SOL_IPV6 = 41 IPV6_RECVDSTADDR = 74 def recv_udp(listener, bufsize): debug3(...
import os import subprocess as ssubprocess from sshuttle.methods import BaseMethod from sshuttle.helpers import log, debug1, debug2, debug3, \ Fatal, family_to_string, get_env, which import socket IP_BINDANY = 24 IP_RECVDSTADDR = 7 SOL_IPV6 = 41 IPV6_RECVDSTADDR = 74 def recv_udp(listener, bufsize): debug3(...
24,731
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle/sshuttle/methods/nat.py
83,84
8,134
restore_firewall
Method
84,121
84,121
class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle at the same time. Of course, # the multiple copies shouldn't have overlapping subnets, or only the most- # recently-started one will win (because we use "-I OUTP...
class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle at the same time. Of course, # the multiple copies shouldn't have overlapping subnets, or only the most- # recently-started one will win (because we use "-I OUTP...
# only ipv4 supported with NAT if family != socket.AF_INET and family != socket.AF_INET6: raise Exception( 'Address family "%s" unsupported by nat method_name' % family_to_string(family)) if udp: raise Exception("UDP not supported by nat me...
# only ipv4 supported with NAT if family != socket.AF_INET and family != socket.AF_INET6: raise Exception( 'Address family "%s" unsupported by nat method_name' % family_to_string(family)) if udp: raise Exception("UDP not supported by nat me...
131
1,046
435
1,481
import socket from sshuttle.firewall import subnet_weight from sshuttle.helpers import family_to_string, which, debug2 from sshuttle.linux import ipt, ipt_chain_exists, nonfatal from sshuttle.methods import BaseMethod class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's ...
import socket from sshuttle.firewall import subnet_weight from sshuttle.helpers import family_to_string, which, debug2 from sshuttle.linux import ipt, ipt_chain_exists, nonfatal from sshuttle.methods import BaseMethod class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's ...
24,735
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle/sshuttle/options.py
155,156
154,174
convert_arg_line_to_args
MyArgumentParser
156,174
156,174
class MyArgumentParser(ArgumentParser): def convert_arg_line_to_args(self, arg_line): FILL_FUNC_BODY
class MyArgumentParser(ArgumentParser): def convert_arg_line_to_args(self, arg_line): FILL_FUNC_BODY
# Ignore comments if arg_line.startswith("#"): return [] # strip whitespace at beginning and end of line arg_line = arg_line.strip() # When copying parameters from the command line to a file, # some users might copy the quotes they used on the command ...
# Ignore comments if arg_line.startswith("#"): return [] # strip whitespace at beginning and end of line arg_line = arg_line.strip() # When copying parameters from the command line to a file, # some users might copy the quotes they used on the command ...
76
38
195
233
import re import socket from argparse import ArgumentParser, Action, ArgumentTypeError as Fatal from sshuttle import __version__ # Subnet file, supporting empty lines and hash-started comment lines def parse_subnetport_file(s): try: handle = open(s, 'r') except OSError: raise Fatal('Unable to...
import re import socket from argparse import ArgumentParser, Action, ArgumentTypeError as Fatal from sshuttle import __version__ # Subnet file, supporting empty lines and hash-started comment lines def parse_subnetport_file(s): try: handle = open(s, 'r') except OSError: raise Fatal('Unable to...
24,736
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle/sshuttle/sdnotify.py
17,18
1,64
_notify
19,44
18,44
"""When sshuttle is run via a systemd service file, we can communicate to systemd about the status of the sshuttle process. In particular, we can send READY status to tell systemd that sshuttle has completed startup and send STOPPING to indicate that sshuttle is beginning shutdown. For details, see: https://www.freede...
"""When sshuttle is run via a systemd service file, we can communicate to systemd about the status of the sshuttle process. In particular, we can send READY status to tell systemd that sshuttle has completed startup and send STOPPING to indicate that sshuttle is beginning shutdown. For details, see: https://www.freede...
addr = os.environ.get("NOTIFY_SOCKET", None) if not addr or len(addr) == 1 or addr[0] not in ('/', '@'): return False addr = '\0' + addr[1:] if addr[0] == '@' else addr try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) except (OSError, IOError) as e: debug1("Err...
"""Send a notification message to systemd.""" addr = os.environ.get("NOTIFY_SOCKET", None) if not addr or len(addr) == 1 or addr[0] not in ('/', '@'): return False addr = '\0' + addr[1:] if addr[0] == '@' else addr try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) e...
78
296
247
543
"""When sshuttle is run via a systemd service file, we can communicate to systemd about the status of the sshuttle process. In particular, we can send READY status to tell systemd that sshuttle has completed startup and send STOPPING to indicate that sshuttle is beginning shutdown. For details, see: https://www.freede...
"""When sshuttle is run via a systemd service file, we can communicate to systemd about the status of the sshuttle process. In particular, we can send READY status to tell systemd that sshuttle has completed startup and send STOPPING to indicate that sshuttle is beginning shutdown. For details, see: https://www.freede...
24,738
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle/sshuttle/ssyslog.py
24,25
1,32
stdout_to_syslog
25,29
25,29
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): global _p with open(os.devnull, 'w') as devnull: _p = ssubprocess.Popen( ['logger', '-p', 'daemon.err', '-t', 'sshuttle'], stdin=ssubprocess.PIPE, stdout=devnull, stder...
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): global _p with open(os.devnull, 'w') as devnull: _p = ssubprocess.Popen( ['logger', '-p', 'daemon.err', '-t', 'sshuttle'], stdin=ssubprocess.PIPE, stdout=devnull, stder...
sys.stdout.flush() os.dup2(_p.stdin.fileno(), sys.stdout.fileno())
sys.stdout.flush() os.dup2(_p.stdin.fileno(), sys.stdout.fileno())
3
198
39
237
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): global _p with open(os.devnull, 'w') as devnull: _p = ssubprocess.Popen( ['logger', '-p', 'daemon.err', '-t', 'sshuttle'], stdin=ssubprocess.PIPE, stdout=devnull, stder...
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): global _p with open(os.devnull, 'w') as devnull: _p = ssubprocess.Popen( ['logger', '-p', 'daemon.err', '-t', 'sshuttle'], stdin=ssubprocess.PIPE, stdout=devnull, stder...
24,739
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/sshuttle_sshuttle/sshuttle/sshuttle/sudoers.py
7,8
1,47
build_config
8,42
8,42
import os import sys import getpass from uuid import uuid4 def build_config(user_name): FILL_FUNC_BODYdef sudoers(user_name=None): user_name = user_name or getpass.getuser() content = build_config(user_name) sys.stdout.write(content) exit(0)
import os import sys import getpass from uuid import uuid4 def build_config(user_name): FILL_FUNC_BODYdef sudoers(user_name=None): user_name = user_name or getpass.getuser() content = build_config(user_name) sys.stdout.write(content) exit(0)
template = ''' # WARNING: If you intend to restrict a user to only running the # sshuttle command as root, THIS CONFIGURATION IS INSECURE. # When a user can run sshuttle as root (with or without a password), # they can also run other commands as root because sshuttle itself # can run a command specified by the user...
template = ''' # WARNING: If you intend to restrict a user to only running the # sshuttle command as root, THIS CONFIGURATION IS INSECURE. # When a user can run sshuttle as root (with or without a password), # they can also run other commands as root because sshuttle itself # can run a command specified by the user...
181
96
465
561
import os import sys import getpass from uuid import uuid4 def build_config(user_name): FILL_FUNC_BODYdef sudoers(user_name=None): user_name = user_name or getpass.getuser() content = build_config(user_name) sys.stdout.write(content) exit(0)
import os import sys import getpass from uuid import uuid4 def build_config(user_name): FILL_FUNC_BODYdef sudoers(user_name=None): user_name = user_name or getpass.getuser() content = build_config(user_name) sys.stdout.write(content) exit(0)
24,744
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/anthropic.py
29,30
1,127
giveup_hdlr
31,36
30,36
import logging import os from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import anthropic anthropic_rate_limit = anthropic.RateLimitError except ImportError: anthropic_rate_limit = Exception logger = logging.getLogger(__name__) BASE_URL = "https://api.anthropic.com/v1...
import logging import os from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import anthropic anthropic_rate_limit = anthropic.RateLimitError except ImportError: anthropic_rate_limit = Exception logger = logging.getLogger(__name__) BASE_URL = "https://api.anthropic.com/v1...
if "rate limits" in details.message: return False return True
"""Wrapper function that decides when to give up on retry.""" if "rate limits" in details.message: return False return True
9
1,314
27
1,341
import logging import os from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import anthropic anthropic_rate_limit = anthropic.RateLimitError except ImportError: anthropic_rate_limit = Exception logger = logging.getLogger(__name__) BASE_URL = "https://api.anthropic.com/v1...
import logging import os from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import anthropic anthropic_rate_limit = anthropic.RateLimitError except ImportError: anthropic_rate_limit = Exception logger = logging.getLogger(__name__) BASE_URL = "https://api.anthropic.com/v1...
24,745
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/anthropic.py
74,75
36,127
basic_request
Claude
75,90
75,90
class Claude(LM): """Wrapper around anthropic's API. Supports both the Anthropic and Azure APIs.""" def __init__( self, model: str = "claude-3-opus-20240229", api_key: Optional[str] = None, api_base: Optional[str] = None, **kwargs, ): super().__init__(model) ...
class Claude(LM): """Wrapper around anthropic's API. Supports both the Anthropic and Azure APIs.""" def __init__( self, model: str = "claude-3-opus-20240229", api_key: Optional[str] = None, api_base: Optional[str] = None, **kwargs, ): super().__init__(model) ...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} # caching mechanism requires hashable kwargs kwargs["messages"] = [{"role": "user", "content": prompt}] kwargs.pop("n") response = self.client.messages.create(**kwargs) history = { "prompt": prompt...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} # caching mechanism requires hashable kwargs kwargs["messages"] = [{"role": "user", "content": prompt}] kwargs.pop("n") response = self.client.messages.create(**kwargs) history = { "prompt": prompt...
38
954
155
1,109
import logging import os from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import anthropic anthropic_rate_limit = anthropic.RateLimitError except ImportError: anthropic_rate_limit = Exception logger = logging.getLogger(__name__) BASE_URL = "https://api.anthropic.com/v1...
import logging import os from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import anthropic anthropic_rate_limit = anthropic.RateLimitError except ImportError: anthropic_rate_limit = Exception logger = logging.getLogger(__name__) BASE_URL = "https://api.anthropic.com/v1...
24,746
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/aws_models.py
244,245
189,254
_call_model
AWSAnthropic
245,254
245,254
class AWSAnthropic(AWSModel): """Anthropic family of models.""" def __init__( self, aws_provider: AWSProvider, model: str, max_context_size: int = 200000, max_new_tokens: int = 1500, **kwargs, ) -> None: """NOTE: Configure your AWS credentials with th...
class AWSAnthropic(AWSModel): """Anthropic family of models.""" def __init__( self, aws_provider: AWSProvider, model: str, max_context_size: int = 200000, max_new_tokens: int = 1500, **kwargs, ) -> None: """NOTE: Configure your AWS credentials with th...
response = self.aws_provider.predictor.invoke_model( modelId=self._model_name, body=body, ) response_body = json.loads(response["body"].read()) completion = response_body["content"][0]["text"] return completion
response = self.aws_provider.predictor.invoke_model( modelId=self._model_name, body=body, ) response_body = json.loads(response["body"].read()) completion = response_body["content"][0]["text"] return completion
14
577
85
662
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
24,747
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/aws_models.py
280,281
254,308
_create_body
AWSMeta
281,296
281,296
class AWSMeta(AWSModel): """Llama2 family of models.""" def __init__( self, aws_provider: AWSProvider, model: str, max_context_size: int = 4096, max_new_tokens: int = 1500, **kwargs, ) -> None: """NOTE: Configure your AWS credentials with the AWS CLI ...
class AWSMeta(AWSModel): """Llama2 family of models.""" def __init__( self, aws_provider: AWSProvider, model: str, max_context_size: int = 4096, max_new_tokens: int = 1500, **kwargs, ) -> None: """NOTE: Configure your AWS credentials with the AWS CLI ...
base_args: dict[str, Any] = self.kwargs for k, v in kwargs.items(): base_args[k] = v n, query_args = self.aws_provider.sanitize_kwargs(base_args) # Meta models do not support the following parameters query_args.pop("frequency_penalty", None) query_args.pop("...
base_args: dict[str, Any] = self.kwargs for k, v in kwargs.items(): base_args[k] = v n, query_args = self.aws_provider.sanitize_kwargs(base_args) # Meta models do not support the following parameters query_args.pop("frequency_penalty", None) query_args.pop("...
40
393
176
569
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
24,748
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/aws_models.py
171,172
127,189
_call_model
AWSMistral
172,189
172,189
class AWSMistral(AWSModel): """Mistral family of models.""" def __init__( self, aws_provider: AWSProvider, model: str, max_context_size: int = 32768, max_new_tokens: int = 1500, **kwargs, ) -> None: """NOTE: Configure your AWS credentials with the AWS...
class AWSMistral(AWSModel): """Mistral family of models.""" def __init__( self, aws_provider: AWSProvider, model: str, max_context_size: int = 32768, max_new_tokens: int = 1500, **kwargs, ) -> None: """NOTE: Configure your AWS credentials with the AWS...
response = self.aws_provider.call_model( model_id=self._model_name, body=body, ) if isinstance(self.aws_provider, Bedrock): response_body = json.loads(response["body"].read()) completion = response_body["outputs"][0]["text"] elif isinstance...
response = self.aws_provider.call_model( model_id=self._model_name, body=body, ) if isinstance(self.aws_provider, Bedrock): response_body = json.loads(response["body"].read()) completion = response_body["outputs"][0]["text"] elif isinstance...
36
496
191
687
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
24,749
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/aws_models.py
96,97
18,127
basic_request
AWSModel
98,108
97,108
class AWSModel(LM): """This class adds support for an AWS model. It is an abstract class and should not be instantiated directly. Instead, use one of the subclasses - AWSMistral, AWSAnthropic, or AWSMeta. The subclasses implement the abstract methods _create_body and _call_model and work in conjunction ...
class AWSModel(LM): """This class adds support for an AWS model. It is an abstract class and should not be instantiated directly. Instead, use one of the subclasses - AWSMistral, AWSAnthropic, or AWSMeta. The subclasses implement the abstract methods _create_body and _call_model and work in conjunction ...
token_count = self._estimate_tokens(prompt) if token_count > self._max_context_size: logging.info("Error - input tokens %s exceeds max context %s", token_count, self._max_context_size) raise ValueError( f"Error - input tokens {token_count} exceeds max context {sel...
"""Query the endpoint.""" token_count = self._estimate_tokens(prompt) if token_count > self._max_context_size: logging.info("Error - input tokens %s exceeds max context %s", token_count, self._max_context_size) raise ValueError( f"Error - input tokens {tok...
37
1,178
154
1,332
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
"""AWS models for LMs.""" from __future__ import annotations import json import logging from abc import abstractmethod from typing import Any from dsp.modules.aws_providers import AWSProvider, Bedrock, Sagemaker from dsp.modules.lm import LM # Heuristic translating number of chars to tokens # ~4 chars = 1 token CHA...
24,750
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/aws_providers.py
58,59
7,80
sanitize_kwargs
AWSProvider
60,80
59,80
class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work in conjunction with the AWSModel classes. Usage Example: bedrock = dspy.Bedrock(region_na...
class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work in conjunction with the AWSModel classes. Usage Example: bedrock = dspy.Bedrock(region_na...
if "temperature" in query_kwargs: if query_kwargs["temperature"] > 0.99: query_kwargs["temperature"] = 0.99 if query_kwargs["temperature"] < 0.01: query_kwargs["temperature"] = 0.01 if "top_p" in query_kwargs: if query_kwargs["top_p"] ...
"""Ensure that input kwargs can be used by Bedrock or Sagemaker.""" if "temperature" in query_kwargs: if query_kwargs["temperature"] > 0.99: query_kwargs["temperature"] = 0.99 if query_kwargs["temperature"] < 0.01: query_kwargs["temperature"] = 0.0...
52
726
223
949
"""AWS providers for LMs.""" from abc import ABC, abstractmethod from typing import Any, Optional class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work ...
"""AWS providers for LMs.""" from abc import ABC, abstractmethod from typing import Any, Optional class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work ...
24,751
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/aws_providers.py
97,98
80,106
call_model
Bedrock
98,106
98,106
class Bedrock(AWSProvider): """This class adds support for Bedrock models.""" def __init__( self, region_name: str, profile_name: Optional[str] = None, batch_n_enabled: bool = False, # This has to be setup manually on Bedrock. ) -> None: """_summary_. Args...
class Bedrock(AWSProvider): """This class adds support for Bedrock models.""" def __init__( self, region_name: str, profile_name: Optional[str] = None, batch_n_enabled: bool = False, # This has to be setup manually on Bedrock. ) -> None: """_summary_. Args...
return self.predictor.invoke_model( modelId=model_id, body=body, accept="application/json", contentType="application/json", )
return self.predictor.invoke_model( modelId=model_id, body=body, accept="application/json", contentType="application/json", )
7
193
59
252
"""AWS providers for LMs.""" from abc import ABC, abstractmethod from typing import Any, Optional class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work ...
"""AWS providers for LMs.""" from abc import ABC, abstractmethod from typing import Any, Optional class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work ...
24,752
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/aws_providers.py
122,123
106,129
call_model
Sagemaker
123,129
123,129
class Sagemaker(AWSProvider): """This class adds support for Sagemaker models.""" def __init__( self, region_name: str, profile_name: Optional[str] = None, ) -> None: """_summary_. Args: region_name (str, optional): The AWS region where this LM is hosted...
class Sagemaker(AWSProvider): """This class adds support for Sagemaker models.""" def __init__( self, region_name: str, profile_name: Optional[str] = None, ) -> None: """_summary_. Args: region_name (str, optional): The AWS region where this LM is hosted...
return self.predictor.invoke_endpoint( EndpointName=model_id, Body=body, Accept="application/json", ContentType="application/json", )
return self.predictor.invoke_endpoint( EndpointName=model_id, Body=body, Accept="application/json", ContentType="application/json", )
7
171
58
229
"""AWS providers for LMs.""" from abc import ABC, abstractmethod from typing import Any, Optional class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work ...
"""AWS providers for LMs.""" from abc import ABC, abstractmethod from typing import Any, Optional class AWSProvider(ABC): """This abstract class adds support for AWS model providers such as Bedrock and SageMaker. The subclasses such as Bedrock and Sagemaker implement the abstract method _call_model and work ...
24,753
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/azurecognitivesearch.py
62,63
1,78
process_azure_result
66,78
63,78
from typing import Any, Union from dsp.utils import dotdict try: from azure.core.credentials import AzureKeyCredential from azure.search.documents import SearchClient from azure.search.documents._paging import SearchItemPaged except ImportError: raise ImportError( "You need to install azure-se...
from typing import Any, Union from dsp.utils import dotdict try: from azure.core.credentials import AzureKeyCredential from azure.search.documents import SearchClient from azure.search.documents._paging import SearchItemPaged except ImportError: raise ImportError( "You need to install azure-se...
res = [] for result in results: tmp = {} for key, value in result.items(): if(key == content_key): tmp["text"] = value # assign content elif(key == content_score): tmp["score"] = value else: tmp[key] = value ...
''' process received result from Azure Cognitive Search as dictionary array and map content and score to correct format ''' res = [] for result in results: tmp = {} for key, value in result.items(): if(key == content_key): tmp["text"] = value # assign cont...
37
805
103
908
from typing import Any, Union from dsp.utils import dotdict try: from azure.core.credentials import AzureKeyCredential from azure.search.documents import SearchClient from azure.search.documents._paging import SearchItemPaged except ImportError: raise ImportError( "You need to install azure-se...
from typing import Any, Union from dsp.utils import dotdict try: from azure.core.credentials import AzureKeyCredential from azure.search.documents import SearchClient from azure.search.documents._paging import SearchItemPaged except ImportError: raise ImportError( "You need to install azure-se...
24,754
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/cache_utils.py
12,13
1,43
noop_decorator
13,26
13,26
import os from functools import wraps from pathlib import Path from joblib import Memory from dsp.utils import dotdict cache_turn_on = os.environ.get('DSP_CACHEBOOL', 'True').lower() != 'false' def noop_decorator(arg=None, *noop_args, **noop_kwargs): FILL_FUNC_BODYcachedir = os.environ.get('DSP_CACHEDIR') or os.pa...
import os from functools import wraps from pathlib import Path from joblib import Memory from dsp.utils import dotdict cache_turn_on = os.environ.get('DSP_CACHEBOOL', 'True').lower() != 'false' def noop_decorator(arg=None, *noop_args, **noop_kwargs): FILL_FUNC_BODYcachedir = os.environ.get('DSP_CACHEDIR') or os.pa...
def decorator(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper if callable(arg): return decorator(arg) else: return decorator
def decorator(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper if callable(arg): return decorator(arg) else: return decorator
18
292
82
374
import os from functools import wraps from pathlib import Path from joblib import Memory from dsp.utils import dotdict cache_turn_on = os.environ.get('DSP_CACHEBOOL', 'True').lower() != 'false' def noop_decorator(arg=None, *noop_args, **noop_kwargs): FILL_FUNC_BODYcachedir = os.environ.get('DSP_CACHEDIR') or os.pa...
import os from functools import wraps from pathlib import Path from joblib import Memory from dsp.utils import dotdict cache_turn_on = os.environ.get('DSP_CACHEBOOL', 'True').lower() != 'false' def noop_decorator(arg=None, *noop_args, **noop_kwargs): FILL_FUNC_BODYcachedir = os.environ.get('DSP_CACHEDIR') or os.pa...
24,755
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/clarifai.py
53,54
7,96
basic_request
ClarifaiLLM
54,75
54,75
class ClarifaiLLM(LM): """Integration to call models hosted in clarifai platform. Args: model (str, optional): Clarifai URL of the model. Defaults to "Mistral-7B-Instruct". api_key (Optional[str], optional): CLARIFAI_PAT token. Defaults to None. **kwargs: Additional arguments to pass to...
class ClarifaiLLM(LM): """Integration to call models hosted in clarifai platform. Args: model (str, optional): Clarifai URL of the model. Defaults to "Mistral-7B-Instruct". api_key (Optional[str], optional): CLARIFAI_PAT token. Defaults to None. **kwargs: Additional arguments to pass to...
params = ( self.kwargs["inference_params"] if "inference_params" in self.kwargs else {} ) response = ( self._model.predict_by_bytes( input_bytes=prompt.encode(encoding="utf-8"), input_type="text", inference_params=params, ...
params = ( self.kwargs["inference_params"] if "inference_params" in self.kwargs else {} ) response = ( self._model.predict_by_bytes( input_bytes=prompt.encode(encoding="utf-8"), input_type="text", inference_params=params, ...
39
698
189
887
"""Clarifai LM integration""" from typing import Any, Optional from dsp.modules.lm import LM class ClarifaiLLM(LM): """Integration to call models hosted in clarifai platform. Args: model (str, optional): Clarifai URL of the model. Defaults to "Mistral-7B-Instruct". api_key (Optional[str], op...
"""Clarifai LM integration""" from typing import Any, Optional from dsp.modules.lm import LM class ClarifaiLLM(LM): """Integration to call models hosted in clarifai platform. Args: model (str, optional): Clarifai URL of the model. Defaults to "Mistral-7B-Instruct". api_key (Optional[str], op...