repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
thomasbiddle/Kippt-for-Python
kippt/clips.py
Clip.like
def like(self): """ Like a clip. """ r = requests.post( "https://kippt.com/api/clips/%s/likes" % (self.id), headers=self.kippt.header ) return (r.json())
python
def like(self): """ Like a clip. """ r = requests.post( "https://kippt.com/api/clips/%s/likes" % (self.id), headers=self.kippt.header ) return (r.json())
[ "def", "like", "(", "self", ")", ":", "r", "=", "requests", ".", "post", "(", "\"https://kippt.com/api/clips/%s/likes\"", "%", "(", "self", ".", "id", ")", ",", "headers", "=", "self", ".", "kippt", ".", "header", ")", "return", "(", "r", ".", "json", ...
Like a clip.
[ "Like", "a", "clip", "." ]
train
https://github.com/thomasbiddle/Kippt-for-Python/blob/dddd0ff84d70ccf2d84e50e3cff7aad89f9c1267/kippt/clips.py#L167-L175
thomasbiddle/Kippt-for-Python
kippt/clips.py
Clip.comment
def comment(self, body): """ Comment on a clip. Parameters: - body (Required) """ # Merge our url as a parameter and JSONify it. data = json.dumps({'body': body}) r = requests.post( "https://kippt.com/api/clips/%s/comments" (self.id), head...
python
def comment(self, body): """ Comment on a clip. Parameters: - body (Required) """ # Merge our url as a parameter and JSONify it. data = json.dumps({'body': body}) r = requests.post( "https://kippt.com/api/clips/%s/comments" (self.id), head...
[ "def", "comment", "(", "self", ",", "body", ")", ":", "# Merge our url as a parameter and JSONify it.", "data", "=", "json", ".", "dumps", "(", "{", "'body'", ":", "body", "}", ")", "r", "=", "requests", ".", "post", "(", "\"https://kippt.com/api/clips/%s/commen...
Comment on a clip. Parameters: - body (Required)
[ "Comment", "on", "a", "clip", "." ]
train
https://github.com/thomasbiddle/Kippt-for-Python/blob/dddd0ff84d70ccf2d84e50e3cff7aad89f9c1267/kippt/clips.py#L187-L200
thomasbiddle/Kippt-for-Python
kippt/clips.py
Clip.unlike
def unlike(self): """ Unlike a clip. """ r = requests.delete( "https://kippt.com/api/clips/%s/likes" % (self.id), headers=self.kippt.header) return (r.json())
python
def unlike(self): """ Unlike a clip. """ r = requests.delete( "https://kippt.com/api/clips/%s/likes" % (self.id), headers=self.kippt.header) return (r.json())
[ "def", "unlike", "(", "self", ")", ":", "r", "=", "requests", ".", "delete", "(", "\"https://kippt.com/api/clips/%s/likes\"", "%", "(", "self", ".", "id", ")", ",", "headers", "=", "self", ".", "kippt", ".", "header", ")", "return", "(", "r", ".", "jso...
Unlike a clip.
[ "Unlike", "a", "clip", "." ]
train
https://github.com/thomasbiddle/Kippt-for-Python/blob/dddd0ff84d70ccf2d84e50e3cff7aad89f9c1267/kippt/clips.py#L223-L230
jayclassless/basicserial
src/basicserial/__init__.py
to_json
def to_json(value, pretty=False): """ Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str """ opt...
python
def to_json(value, pretty=False): """ Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str """ opt...
[ "def", "to_json", "(", "value", ",", "pretty", "=", "False", ")", ":", "options", "=", "{", "'sort_keys'", ":", "False", ",", "'cls'", ":", "BasicJSONEncoder", ",", "}", "if", "pretty", ":", "options", "[", "'indent'", "]", "=", "2", "options", "[", ...
Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str
[ "Serializes", "the", "given", "value", "to", "JSON", "." ]
train
https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L80-L100
jayclassless/basicserial
src/basicserial/__init__.py
from_json
def from_json(value, native_datetimes=True): """ Deserializes the given value from JSON. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as ...
python
def from_json(value, native_datetimes=True): """ Deserializes the given value from JSON. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as ...
[ "def", "from_json", "(", "value", ",", "native_datetimes", "=", "True", ")", ":", "hook", "=", "BasicJsonDecoder", "(", "native_datetimes", "=", "native_datetimes", ")", "result", "=", "json", ".", "loads", "(", "value", ",", "object_hook", "=", "hook", ")",...
Deserializes the given value from JSON. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as strings; if not specified, defaults to ``True`` ...
[ "Deserializes", "the", "given", "value", "from", "JSON", "." ]
train
https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L173-L190
jayclassless/basicserial
src/basicserial/__init__.py
to_yaml
def to_yaml(value, pretty=False): """ Serializes the given value to YAML. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str """ if ...
python
def to_yaml(value, pretty=False): """ Serializes the given value to YAML. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str """ if ...
[ "def", "to_yaml", "(", "value", ",", "pretty", "=", "False", ")", ":", "if", "not", "yaml", ":", "raise", "NotImplementedError", "(", "'No supported YAML library available'", ")", "options", "=", "{", "'Dumper'", ":", "BasicYamlDumper", ",", "'allow_unicode'", "...
Serializes the given value to YAML. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str
[ "Serializes", "the", "given", "value", "to", "YAML", "." ]
train
https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L244-L265
jayclassless/basicserial
src/basicserial/__init__.py
from_yaml
def from_yaml(value, native_datetimes=True): """ Deserializes the given value from YAML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as ...
python
def from_yaml(value, native_datetimes=True): """ Deserializes the given value from YAML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as ...
[ "def", "from_yaml", "(", "value", ",", "native_datetimes", "=", "True", ")", ":", "if", "not", "yaml", ":", "raise", "NotImplementedError", "(", "'No supported YAML library available'", ")", "if", "native_datetimes", ":", "loader", "=", "NativeDatesYamlLoader", "els...
Deserializes the given value from YAML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as strings; if not specified, defaults to ``True`` ...
[ "Deserializes", "the", "given", "value", "from", "YAML", "." ]
train
https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L302-L323
jayclassless/basicserial
src/basicserial/__init__.py
to_toml
def to_toml(value, pretty=False): # noqa: unused-argument """ Serializes the given value to TOML. :param value: the value to serialize :param pretty: this argument is ignored, as no TOML libraries support this type of operation :type pretty: bool :rtype: str """ if not...
python
def to_toml(value, pretty=False): # noqa: unused-argument """ Serializes the given value to TOML. :param value: the value to serialize :param pretty: this argument is ignored, as no TOML libraries support this type of operation :type pretty: bool :rtype: str """ if not...
[ "def", "to_toml", "(", "value", ",", "pretty", "=", "False", ")", ":", "# noqa: unused-argument", "if", "not", "toml", ":", "raise", "NotImplementedError", "(", "'No supported TOML library available'", ")", "return", "toml", ".", "dumps", "(", "make_toml_friendly", ...
Serializes the given value to TOML. :param value: the value to serialize :param pretty: this argument is ignored, as no TOML libraries support this type of operation :type pretty: bool :rtype: str
[ "Serializes", "the", "given", "value", "to", "TOML", "." ]
train
https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L354-L369
jayclassless/basicserial
src/basicserial/__init__.py
from_toml
def from_toml(value, native_datetimes=True): """ Deserializes the given value from TOML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as ...
python
def from_toml(value, native_datetimes=True): """ Deserializes the given value from TOML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as ...
[ "def", "from_toml", "(", "value", ",", "native_datetimes", "=", "True", ")", ":", "if", "not", "toml", ":", "raise", "NotImplementedError", "(", "'No supported TOML library available'", ")", "result", "=", "toml", ".", "loads", "(", "value", ")", "if", "native...
Deserializes the given value from TOML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as strings; if not specified, defaults to ``True`` ...
[ "Deserializes", "the", "given", "value", "from", "TOML", "." ]
train
https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L372-L393
MacHu-GWU/inspect_mate-project
dev/analysis.py
export_true_table
def export_true_table(): """Export value, checker function output true table. Help to organize thought. klass.__dict__ 指的是在类定义中定义的, 从父类继承而来的不在此中。 """ tester_list = [ ("inspect.isroutine", lambda v: inspect.isroutine(v)), ("inspect.isfunction", lambda v: inspect.isfunction(v)), ...
python
def export_true_table(): """Export value, checker function output true table. Help to organize thought. klass.__dict__ 指的是在类定义中定义的, 从父类继承而来的不在此中。 """ tester_list = [ ("inspect.isroutine", lambda v: inspect.isroutine(v)), ("inspect.isfunction", lambda v: inspect.isfunction(v)), ...
[ "def", "export_true_table", "(", ")", ":", "tester_list", "=", "[", "(", "\"inspect.isroutine\"", ",", "lambda", "v", ":", "inspect", ".", "isroutine", "(", "v", ")", ")", ",", "(", "\"inspect.isfunction\"", ",", "lambda", "v", ":", "inspect", ".", "isfunc...
Export value, checker function output true table. Help to organize thought. klass.__dict__ 指的是在类定义中定义的, 从父类继承而来的不在此中。
[ "Export", "value", "checker", "function", "output", "true", "table", ".", "Help", "to", "organize", "thought", ".", "klass", ".", "__dict__", "指的是在类定义中定义的", "从父类继承而来的不在此中。" ]
train
https://github.com/MacHu-GWU/inspect_mate-project/blob/a3d0980ee259daf578bb2226fea311af08ab435b/dev/analysis.py#L33-L101
MacHu-GWU/inspect_mate-project
dev/analysis.py
merge_true_table
def merge_true_table(): """Merge all true table into single excel file. """ writer = pd.ExcelWriter("True Table.xlsx") for p in Path(__file__).parent.select_by_ext(".csv"): df = pd.read_csv(p.abspath, index_col=0) df.to_excel(writer, p.fname, index=True) writer.save()
python
def merge_true_table(): """Merge all true table into single excel file. """ writer = pd.ExcelWriter("True Table.xlsx") for p in Path(__file__).parent.select_by_ext(".csv"): df = pd.read_csv(p.abspath, index_col=0) df.to_excel(writer, p.fname, index=True) writer.save()
[ "def", "merge_true_table", "(", ")", ":", "writer", "=", "pd", ".", "ExcelWriter", "(", "\"True Table.xlsx\"", ")", "for", "p", "in", "Path", "(", "__file__", ")", ".", "parent", ".", "select_by_ext", "(", "\".csv\"", ")", ":", "df", "=", "pd", ".", "r...
Merge all true table into single excel file.
[ "Merge", "all", "true", "table", "into", "single", "excel", "file", "." ]
train
https://github.com/MacHu-GWU/inspect_mate-project/blob/a3d0980ee259daf578bb2226fea311af08ab435b/dev/analysis.py#L107-L114
kblin/aio-standalone
aiostandalone/signal.py
Signal.send
async def send(self, *args, **kwargs): """Send args and kwargs to all registered callbacks""" for callback in self: res = callback(*args, **kwargs) if asyncio.iscoroutine(res) or isinstance(res, asyncio.Future): await res
python
async def send(self, *args, **kwargs): """Send args and kwargs to all registered callbacks""" for callback in self: res = callback(*args, **kwargs) if asyncio.iscoroutine(res) or isinstance(res, asyncio.Future): await res
[ "async", "def", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "callback", "in", "self", ":", "res", "=", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "asyncio", ".", "iscoroutine", "(", "res...
Send args and kwargs to all registered callbacks
[ "Send", "args", "and", "kwargs", "to", "all", "registered", "callbacks" ]
train
https://github.com/kblin/aio-standalone/blob/21f7212ee23e7c2dff679fbf3e9c8d9acf77b568/aiostandalone/signal.py#L20-L25
webadmin87/midnight
midnight_catalog/templatetags/midnight_catalog.py
param_value
def param_value(param_values, slug): """ Отображает значение параметра товара Пример использования:: {% param_value item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return: """ for val in param_values:...
python
def param_value(param_values, slug): """ Отображает значение параметра товара Пример использования:: {% param_value item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return: """ for val in param_values:...
[ "def", "param_value", "(", "param_values", ",", "slug", ")", ":", "for", "val", "in", "param_values", ":", "if", "val", ".", "param", ".", "slug", "==", "slug", ":", "return", "val", ".", "value", "return", "None" ]
Отображает значение параметра товара Пример использования:: {% param_value item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return:
[ "Отображает", "значение", "параметра", "товара" ]
train
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_catalog/templatetags/midnight_catalog.py#L13-L28
webadmin87/midnight
midnight_catalog/templatetags/midnight_catalog.py
param_title
def param_title(param_values, slug): """ Отображает наименование параметра товара Пример использования:: {% param_title item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return: """ for val in param_val...
python
def param_title(param_values, slug): """ Отображает наименование параметра товара Пример использования:: {% param_title item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return: """ for val in param_val...
[ "def", "param_title", "(", "param_values", ",", "slug", ")", ":", "for", "val", "in", "param_values", ":", "if", "val", ".", "param", ".", "slug", "==", "slug", ":", "return", "val", ".", "param", ".", "title", "return", "None" ]
Отображает наименование параметра товара Пример использования:: {% param_title item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return:
[ "Отображает", "наименование", "параметра", "товара" ]
train
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_catalog/templatetags/midnight_catalog.py#L32-L47
webadmin87/midnight
midnight_catalog/templatetags/midnight_catalog.py
currency
def currency(money): """ Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой, а также добавлеят символ валюты. :param money: :return: """ decimals = getattr(settings, 'MIDNIGHT_CATALOG_DECIMALS', 2) money = round(float(money), decimals) sym...
python
def currency(money): """ Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой, а также добавлеят символ валюты. :param money: :return: """ decimals = getattr(settings, 'MIDNIGHT_CATALOG_DECIMALS', 2) money = round(float(money), decimals) sym...
[ "def", "currency", "(", "money", ")", ":", "decimals", "=", "getattr", "(", "settings", ",", "'MIDNIGHT_CATALOG_DECIMALS'", ",", "2", ")", "money", "=", "round", "(", "float", "(", "money", ")", ",", "decimals", ")", "symbol", "=", "getattr", "(", "setti...
Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой, а также добавлеят символ валюты. :param money: :return:
[ "Фильтр", "валюты", ".", "Форматирует", "цену", "в", "соответствии", "с", "установленным", "количеством", "знаков", "после", "запятой", "а", "также", "добавлеят", "символ", "валюты", ".", ":", "param", "money", ":", ":", "return", ":" ]
train
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_catalog/templatetags/midnight_catalog.py#L51-L65
webadmin87/midnight
midnight_catalog/templatetags/midnight_catalog.py
catalog_sections
def catalog_sections(context, slug=None, level=3, **kwargs): """ Отображает иерерхический список категорий каталога. Для каждой категории отображается количество содержащегося в ней товара. Пример использования:: {% catalog_sections 'section_slug' 2 class='catalog-class' %} :param context...
python
def catalog_sections(context, slug=None, level=3, **kwargs): """ Отображает иерерхический список категорий каталога. Для каждой категории отображается количество содержащегося в ней товара. Пример использования:: {% catalog_sections 'section_slug' 2 class='catalog-class' %} :param context...
[ "def", "catalog_sections", "(", "context", ",", "slug", "=", "None", ",", "level", "=", "3", ",", "*", "*", "kwargs", ")", ":", "count_products", "=", "Count", "(", "Case", "(", "When", "(", "product__active", "=", "True", ",", "then", "=", "Value", ...
Отображает иерерхический список категорий каталога. Для каждой категории отображается количество содержащегося в ней товара. Пример использования:: {% catalog_sections 'section_slug' 2 class='catalog-class' %} :param context: контекст :param slug: символьный код родительской категории, если н...
[ "Отображает", "иерерхический", "список", "категорий", "каталога", ".", "Для", "каждой", "категории", "отображается", "количество", "содержащегося", "в", "ней", "товара", "." ]
train
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_catalog/templatetags/midnight_catalog.py#L68-L92
inveniosoftware-contrib/record-recommender
record_recommender/app.py
get_config
def get_config(config_path='/etc/record_recommender.yml', sentry=False): """Load the configuration file.""" config = {} if os.path.exists(config_path): with open(config_path, 'rt') as f: config = yaml.safe_load(f.read()) else: # TODO: Auto create config file. print("N...
python
def get_config(config_path='/etc/record_recommender.yml', sentry=False): """Load the configuration file.""" config = {} if os.path.exists(config_path): with open(config_path, 'rt') as f: config = yaml.safe_load(f.read()) else: # TODO: Auto create config file. print("N...
[ "def", "get_config", "(", "config_path", "=", "'/etc/record_recommender.yml'", ",", "sentry", "=", "False", ")", ":", "config", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "config_path", ")", ":", "with", "open", "(", "config_path", ",", ...
Load the configuration file.
[ "Load", "the", "configuration", "file", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/app.py#L47-L70
inveniosoftware-contrib/record-recommender
record_recommender/app.py
setup_logging
def setup_logging(config=None): """Setup logging configuration.""" # TODO: integrate in general config file print(__name__) if config and config.get('logging'): logging.config.dictConfig(config.get('logging')) else: logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', ...
python
def setup_logging(config=None): """Setup logging configuration.""" # TODO: integrate in general config file print(__name__) if config and config.get('logging'): logging.config.dictConfig(config.get('logging')) else: logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', ...
[ "def", "setup_logging", "(", "config", "=", "None", ")", ":", "# TODO: integrate in general config file", "print", "(", "__name__", ")", "if", "config", "and", "config", ".", "get", "(", "'logging'", ")", ":", "logging", ".", "config", ".", "dictConfig", "(", ...
Setup logging configuration.
[ "Setup", "logging", "configuration", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/app.py#L73-L81
inveniosoftware-contrib/record-recommender
record_recommender/app.py
_create_all_recommendations
def _create_all_recommendations(cores, ip_views=False, config=None): """Calculate all recommendations in multiple processes.""" global _reco, _store _reco = GraphRecommender(_store) _reco.load_profile('Profiles') if ip_views: _reco.load_profile('Profiles_IP') manager = Manager() re...
python
def _create_all_recommendations(cores, ip_views=False, config=None): """Calculate all recommendations in multiple processes.""" global _reco, _store _reco = GraphRecommender(_store) _reco.load_profile('Profiles') if ip_views: _reco.load_profile('Profiles_IP') manager = Manager() re...
[ "def", "_create_all_recommendations", "(", "cores", ",", "ip_views", "=", "False", ",", "config", "=", "None", ")", ":", "global", "_reco", ",", "_store", "_reco", "=", "GraphRecommender", "(", "_store", ")", "_reco", ".", "load_profile", "(", "'Profiles'", ...
Calculate all recommendations in multiple processes.
[ "Calculate", "all", "recommendations", "in", "multiple", "processes", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/app.py#L109-L145
inveniosoftware-contrib/record-recommender
record_recommender/app.py
RecordRecommender.fetch_weeks
def fetch_weeks(self, weeks, overwrite=False): """Fetch and cache the requested weeks.""" esf = ElasticsearchFetcher(self.store, self.config) for year, week in weeks: print("Fetch {}-{}".format(year, week)) esf.fetch(year, week, overwrite)
python
def fetch_weeks(self, weeks, overwrite=False): """Fetch and cache the requested weeks.""" esf = ElasticsearchFetcher(self.store, self.config) for year, week in weeks: print("Fetch {}-{}".format(year, week)) esf.fetch(year, week, overwrite)
[ "def", "fetch_weeks", "(", "self", ",", "weeks", ",", "overwrite", "=", "False", ")", ":", "esf", "=", "ElasticsearchFetcher", "(", "self", ".", "store", ",", "self", ".", "config", ")", "for", "year", ",", "week", "in", "weeks", ":", "print", "(", "...
Fetch and cache the requested weeks.
[ "Fetch", "and", "cache", "the", "requested", "weeks", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/app.py#L95-L100
inveniosoftware-contrib/record-recommender
record_recommender/app.py
RecordRecommender.create_all_recommendations
def create_all_recommendations(self, cores, ip_views=False): """Calculate the recommendations for all records.""" global _store _store = self.store _create_all_recommendations(cores, ip_views, self.config)
python
def create_all_recommendations(self, cores, ip_views=False): """Calculate the recommendations for all records.""" global _store _store = self.store _create_all_recommendations(cores, ip_views, self.config)
[ "def", "create_all_recommendations", "(", "self", ",", "cores", ",", "ip_views", "=", "False", ")", ":", "global", "_store", "_store", "=", "self", ".", "store", "_create_all_recommendations", "(", "cores", ",", "ip_views", ",", "self", ".", "config", ")" ]
Calculate the recommendations for all records.
[ "Calculate", "the", "recommendations", "for", "all", "records", "." ]
train
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/app.py#L102-L106
wdbm/pyprel
pyprel/__init__.py
table_dataset_database_table
def table_dataset_database_table( table = None, include_attributes = None, rows_limit = None, print_progress = False, ): """ Create a pyprel table contents list from a database table of the module dataset. Attributes to be included in the table can be specified;...
python
def table_dataset_database_table( table = None, include_attributes = None, rows_limit = None, print_progress = False, ): """ Create a pyprel table contents list from a database table of the module dataset. Attributes to be included in the table can be specified;...
[ "def", "table_dataset_database_table", "(", "table", "=", "None", ",", "include_attributes", "=", "None", ",", "rows_limit", "=", "None", ",", "print_progress", "=", "False", ",", ")", ":", "if", "print_progress", ":", "import", "shijian", "progress", "=", "sh...
Create a pyprel table contents list from a database table of the module dataset. Attributes to be included in the table can be specified; by default, all attributes are included. A limit on the number of rows included can be specified. Progress on building the table can be reported.
[ "Create", "a", "pyprel", "table", "contents", "list", "from", "a", "database", "table", "of", "the", "module", "dataset", ".", "Attributes", "to", "be", "included", "in", "the", "table", "can", "be", "specified", ";", "by", "default", "all", "attributes", ...
train
https://github.com/wdbm/pyprel/blob/c1253ea3f8c60a2f5493a0d5a61ca3c84df7c21d/pyprel/__init__.py#L275-L317
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/reader.py
read_variables
def read_variables(config_location: str) -> Dict[str, str]: """ Reads variables out of a config file. Variables can be in a ini file, a shell file used to source the variables (i.e. one that has just got "export *" like statements in it) or in JSON. :param config_location: the location of the config fil...
python
def read_variables(config_location: str) -> Dict[str, str]: """ Reads variables out of a config file. Variables can be in a ini file, a shell file used to source the variables (i.e. one that has just got "export *" like statements in it) or in JSON. :param config_location: the location of the config fil...
[ "def", "read_variables", "(", "config_location", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "with", "open", "(", "config_location", ",", "\"r\"", ")", "as", "config_file", ":", "config_lines", "=", "config_file", ".", "readlines", "("...
Reads variables out of a config file. Variables can be in a ini file, a shell file used to source the variables (i.e. one that has just got "export *" like statements in it) or in JSON. :param config_location: the location of the config file :return: dictionary where the variable names are key and their val...
[ "Reads", "variables", "out", "of", "a", "config", "file", ".", "Variables", "can", "be", "in", "a", "ini", "file", "a", "shell", "file", "used", "to", "source", "the", "variables", "(", "i", ".", "e", ".", "one", "that", "has", "just", "got", "export...
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/reader.py#L12-L27
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/reader.py
_read_ini_config
def _read_ini_config(ini_file_contents: str) -> Dict[str, str]: """ Parses the given ini file contents and converts to a dictionary of key/value pairs. :param ini_file_contents: the contents of the ini file :return: dictionary where the variable names are key and their values are the values """ ...
python
def _read_ini_config(ini_file_contents: str) -> Dict[str, str]: """ Parses the given ini file contents and converts to a dictionary of key/value pairs. :param ini_file_contents: the contents of the ini file :return: dictionary where the variable names are key and their values are the values """ ...
[ "def", "_read_ini_config", "(", "ini_file_contents", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "optionxform", "=", "str", "config", ".", "read_string", "(",...
Parses the given ini file contents and converts to a dictionary of key/value pairs. :param ini_file_contents: the contents of the ini file :return: dictionary where the variable names are key and their values are the values
[ "Parses", "the", "given", "ini", "file", "contents", "and", "converts", "to", "a", "dictionary", "of", "key", "/", "value", "pairs", ".", ":", "param", "ini_file_contents", ":", "the", "contents", "of", "the", "ini", "file", ":", "return", ":", "dictionary...
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/reader.py#L30-L44
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/reader.py
_shell_to_ini
def _shell_to_ini(shell_file_contents: List[str]) -> List[str]: """ Converts a shell file, which just contains comments and "export *" statements into an ini file. :param shell_file_contents: the contents of the shell file :return: lines of an equivalent ini file """ line_number = 0 while li...
python
def _shell_to_ini(shell_file_contents: List[str]) -> List[str]: """ Converts a shell file, which just contains comments and "export *" statements into an ini file. :param shell_file_contents: the contents of the shell file :return: lines of an equivalent ini file """ line_number = 0 while li...
[ "def", "_shell_to_ini", "(", "shell_file_contents", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "line_number", "=", "0", "while", "line_number", "<", "len", "(", "shell_file_contents", ")", ":", "line", "=", "shell_file_contents", ...
Converts a shell file, which just contains comments and "export *" statements into an ini file. :param shell_file_contents: the contents of the shell file :return: lines of an equivalent ini file
[ "Converts", "a", "shell", "file", "which", "just", "contains", "comments", "and", "export", "*", "statements", "into", "an", "ini", "file", ".", ":", "param", "shell_file_contents", ":", "the", "contents", "of", "the", "shell", "file", ":", "return", ":", ...
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/reader.py#L47-L62
noobermin/lspreader
lspreader/nearest.py
nearest_indices
def nearest_indices(xs, XS): ''' Returns indices that perform nearest interpolation given a set of points. Similar to scipy.interpolate.griddata with method set to "nearest". In fact, it's construction is based on that function and related types. Parameters: ----------- xs -- ndarray o...
python
def nearest_indices(xs, XS): ''' Returns indices that perform nearest interpolation given a set of points. Similar to scipy.interpolate.griddata with method set to "nearest". In fact, it's construction is based on that function and related types. Parameters: ----------- xs -- ndarray o...
[ "def", "nearest_indices", "(", "xs", ",", "XS", ")", ":", "xs", "=", "_ndim_coords_from_arrays", "(", "xs", ")", "XS", "=", "_ndim_coords_from_arrays", "(", "XS", ",", "ndim", "=", "xs", ".", "shape", "[", "1", "]", ")", "if", "XS", ".", "shape", "["...
Returns indices that perform nearest interpolation given a set of points. Similar to scipy.interpolate.griddata with method set to "nearest". In fact, it's construction is based on that function and related types. Parameters: ----------- xs -- ndarray of floats, shape (n,D) Data poin...
[ "Returns", "indices", "that", "perform", "nearest", "interpolation", "given", "a", "set", "of", "points", ".", "Similar", "to", "scipy", ".", "interpolate", ".", "griddata", "with", "method", "set", "to", "nearest", ".", "In", "fact", "it", "s", "constructio...
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/nearest.py#L42-L64
noobermin/lspreader
lspreader/nearest.py
simple_nearest_indices
def simple_nearest_indices(xs,res): ''' Simple nearest interpolator that interpolates based on the minima and maxima of points based on the passed resolution in res. Parameters: ----------- xs -- A collection of `ndim` arrays of points. res -- List of resolutions. ''' maxs = [...
python
def simple_nearest_indices(xs,res): ''' Simple nearest interpolator that interpolates based on the minima and maxima of points based on the passed resolution in res. Parameters: ----------- xs -- A collection of `ndim` arrays of points. res -- List of resolutions. ''' maxs = [...
[ "def", "simple_nearest_indices", "(", "xs", ",", "res", ")", ":", "maxs", "=", "[", "max", "(", "a", ")", "for", "a", "in", "xs", "]", "mins", "=", "[", "min", "(", "a", ")", "for", "a", "in", "xs", "]", "XS", "=", "[", "np", ".", "linspace",...
Simple nearest interpolator that interpolates based on the minima and maxima of points based on the passed resolution in res. Parameters: ----------- xs -- A collection of `ndim` arrays of points. res -- List of resolutions.
[ "Simple", "nearest", "interpolator", "that", "interpolates", "based", "on", "the", "minima", "and", "maxima", "of", "points", "based", "on", "the", "passed", "resolution", "in", "res", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/nearest.py#L66-L84
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.get
def get(self) -> Dict[str, str]: """ Gets the build variables for the project. :return: the build variables """ variables = self._project.variables.list(all=True) return {variable.key: variable.value for variable in variables}
python
def get(self) -> Dict[str, str]: """ Gets the build variables for the project. :return: the build variables """ variables = self._project.variables.list(all=True) return {variable.key: variable.value for variable in variables}
[ "def", "get", "(", "self", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "variables", "=", "self", ".", "_project", ".", "variables", ".", "list", "(", "all", "=", "True", ")", "return", "{", "variable", ".", "key", ":", "variable", ".", "...
Gets the build variables for the project. :return: the build variables
[ "Gets", "the", "build", "variables", "for", "the", "project", ".", ":", "return", ":", "the", "build", "variables" ]
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L43-L49
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.clear
def clear(self): """ Clears all of the build variables. """ for variable in self._project.variables.list(all=True): variable.delete()
python
def clear(self): """ Clears all of the build variables. """ for variable in self._project.variables.list(all=True): variable.delete()
[ "def", "clear", "(", "self", ")", ":", "for", "variable", "in", "self", ".", "_project", ".", "variables", ".", "list", "(", "all", "=", "True", ")", ":", "variable", ".", "delete", "(", ")" ]
Clears all of the build variables.
[ "Clears", "all", "of", "the", "build", "variables", "." ]
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L51-L56
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.remove
def remove(self, variables: Union[Iterable[str], Dict[str, str]]=None): """ Removes the given variables. Will only remove a key if it has the given value if the value has been defined. :param variables: the variables to remove """ keys = list(variables.keys()) if isinstance(varia...
python
def remove(self, variables: Union[Iterable[str], Dict[str, str]]=None): """ Removes the given variables. Will only remove a key if it has the given value if the value has been defined. :param variables: the variables to remove """ keys = list(variables.keys()) if isinstance(varia...
[ "def", "remove", "(", "self", ",", "variables", ":", "Union", "[", "Iterable", "[", "str", "]", ",", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", ":", "keys", "=", "list", "(", "variables", ".", "keys", "(", ")", ")", "if", "isin...
Removes the given variables. Will only remove a key if it has the given value if the value has been defined. :param variables: the variables to remove
[ "Removes", "the", "given", "variables", ".", "Will", "only", "remove", "a", "key", "if", "it", "has", "the", "given", "value", "if", "the", "value", "has", "been", "defined", ".", ":", "param", "variables", ":", "the", "variables", "to", "remove" ]
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L58-L69
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.set
def set(self, variables: Dict[str, str]): """ Sets the build variables (i.e. removes old ones, adds new ones) :param variables: the build variables to set """ current_variables = self.get() difference = DictDiffer(variables, current_variables) removed_keys = diff...
python
def set(self, variables: Dict[str, str]): """ Sets the build variables (i.e. removes old ones, adds new ones) :param variables: the build variables to set """ current_variables = self.get() difference = DictDiffer(variables, current_variables) removed_keys = diff...
[ "def", "set", "(", "self", ",", "variables", ":", "Dict", "[", "str", ",", "str", "]", ")", ":", "current_variables", "=", "self", ".", "get", "(", ")", "difference", "=", "DictDiffer", "(", "variables", ",", "current_variables", ")", "removed_keys", "="...
Sets the build variables (i.e. removes old ones, adds new ones) :param variables: the build variables to set
[ "Sets", "the", "build", "variables", "(", "i", ".", "e", ".", "removes", "old", "ones", "adds", "new", "ones", ")", ":", "param", "variables", ":", "the", "build", "variables", "to", "set" ]
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L71-L84
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/manager.py
ProjectVariablesManager.add
def add(self, variables: Dict[str, str], overwrite: bool=False): """ Adds the given build variables to those that already exist. :param variables: the build variables to add :param overwrite: whether the old variable should be overwritten in the case of a redefinition """ ...
python
def add(self, variables: Dict[str, str], overwrite: bool=False): """ Adds the given build variables to those that already exist. :param variables: the build variables to add :param overwrite: whether the old variable should be overwritten in the case of a redefinition """ ...
[ "def", "add", "(", "self", ",", "variables", ":", "Dict", "[", "str", ",", "str", "]", ",", "overwrite", ":", "bool", "=", "False", ")", ":", "preset_variables", "=", "self", ".", "_project", ".", "variables", ".", "list", "(", ")", "preset_variable_ke...
Adds the given build variables to those that already exist. :param variables: the build variables to add :param overwrite: whether the old variable should be overwritten in the case of a redefinition
[ "Adds", "the", "given", "build", "variables", "to", "those", "that", "already", "exist", ".", ":", "param", "variables", ":", "the", "build", "variables", "to", "add", ":", "param", "overwrite", ":", "whether", "the", "old", "variable", "should", "be", "ov...
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/manager.py#L86-L104
Metatab/tableintuit
tableintuit/types.py
Column._resolved_type
def _resolved_type(self): """Return the type for the columns, and a flag to indicate that the column has codes.""" import datetime self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None for test, testf in tests +...
python
def _resolved_type(self): """Return the type for the columns, and a flag to indicate that the column has codes.""" import datetime self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None for test, testf in tests +...
[ "def", "_resolved_type", "(", "self", ")", ":", "import", "datetime", "self", ".", "type_ratios", "=", "{", "test", ":", "(", "float", "(", "self", ".", "type_counts", "[", "test", "]", ")", "/", "float", "(", "self", ".", "count", ")", ")", "if", ...
Return the type for the columns, and a flag to indicate that the column has codes.
[ "Return", "the", "type", "for", "the", "columns", "and", "a", "flag", "to", "indicate", "that", "the", "column", "has", "codes", "." ]
train
https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/types.py#L242-L293
Metatab/tableintuit
tableintuit/types.py
TypeIntuiter.promote_type
def promote_type(orig_type, new_type): """Given a table with an original type, decide whether a new determination of a new applicable type should overide the existing one""" if not new_type: return orig_type if not orig_type: return new_type try: ...
python
def promote_type(orig_type, new_type): """Given a table with an original type, decide whether a new determination of a new applicable type should overide the existing one""" if not new_type: return orig_type if not orig_type: return new_type try: ...
[ "def", "promote_type", "(", "orig_type", ",", "new_type", ")", ":", "if", "not", "new_type", ":", "return", "orig_type", "if", "not", "orig_type", ":", "return", "new_type", "try", ":", "orig_type", "=", "orig_type", ".", "__name__", "except", "AttributeError"...
Given a table with an original type, decide whether a new determination of a new applicable type should overide the existing one
[ "Given", "a", "table", "with", "an", "original", "type", "decide", "whether", "a", "new", "determination", "of", "a", "new", "applicable", "type", "should", "overide", "the", "existing", "one" ]
train
https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/types.py#L423-L450
shi-cong/PYSTUDY
PYSTUDY/net/requestslib.py
HTTP.filter_duplicate
def filter_duplicate(self, url): """ url去重 """ if self.filterDuplicate: if url in self.historys: raise Exception('duplicate excepiton: %s is duplicate' % url) else: self.historys.add(url) else: pass
python
def filter_duplicate(self, url): """ url去重 """ if self.filterDuplicate: if url in self.historys: raise Exception('duplicate excepiton: %s is duplicate' % url) else: self.historys.add(url) else: pass
[ "def", "filter_duplicate", "(", "self", ",", "url", ")", ":", "if", "self", ".", "filterDuplicate", ":", "if", "url", "in", "self", ".", "historys", ":", "raise", "Exception", "(", "'duplicate excepiton: %s is duplicate'", "%", "url", ")", "else", ":", "self...
url去重
[ "url去重" ]
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/net/requestslib.py#L54-L64
shi-cong/PYSTUDY
PYSTUDY/net/requestslib.py
HTTP.__select
def __select(self, method, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True, encoding='utf-8', params=None, form_data=None, stream=False): """ 对http动作的封装,当传递get,则模拟http get请求, 当传递post, 则模拟http post请求 :param method: 'get' or 'p...
python
def __select(self, method, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True, encoding='utf-8', params=None, form_data=None, stream=False): """ 对http动作的封装,当传递get,则模拟http get请求, 当传递post, 则模拟http post请求 :param method: 'get' or 'p...
[ "def", "__select", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "timeout", "=", "60", ",", "verify", "=", "False", ",", "proxies", "=", "None", ",", "allow_redirects", "=", "True", ",", "encod...
对http动作的封装,当传递get,则模拟http get请求, 当传递post, 则模拟http post请求 :param method: 'get' or 'post' :param url: 访问Url :param headers: 请求头 :param cookies: 请求cookies :param timeout: 超时时间 :param verify: ssl验证 :param proxies: 代理 :param allow_redirects: 是否允许重定向 ...
[ "对http动作的封装,当传递get,则模拟http", "get请求,", "当传递post", "则模拟http", "post请求", ":", "param", "method", ":", "get", "or", "post", ":", "param", "url", ":", "访问Url", ":", "param", "headers", ":", "请求头", ":", "param", "cookies", ":", "请求cookies", ":", "param", "timeout...
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/net/requestslib.py#L76-L123
shi-cong/PYSTUDY
PYSTUDY/net/requestslib.py
HTTP.get
def get(self, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True, encoding='utf-8', params=None, stream=False): """ 模拟http get请求 :param url: 访问Url :param headers: 请求头 :param cookies: 请求cookies :param timeout: 超时时间 ...
python
def get(self, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True, encoding='utf-8', params=None, stream=False): """ 模拟http get请求 :param url: 访问Url :param headers: 请求头 :param cookies: 请求cookies :param timeout: 超时时间 ...
[ "def", "get", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "timeout", "=", "60", ",", "verify", "=", "False", ",", "proxies", "=", "None", ",", "allow_redirects", "=", "True", ",", "encoding", "=", "'utf-8'"...
模拟http get请求 :param url: 访问Url :param headers: 请求头 :param cookies: 请求cookies :param timeout: 超时时间 :param verify: ssl验证 :param proxies: 代理 :param allow_redirects: 是否允许重定向 :param encoding: 返回的html编码 :param params: 查询请求参数 :param stream: 是否为流数据...
[ "模拟http", "get请求", ":", "param", "url", ":", "访问Url", ":", "param", "headers", ":", "请求头", ":", "param", "cookies", ":", "请求cookies", ":", "param", "timeout", ":", "超时时间", ":", "param", "verify", ":", "ssl验证", ":", "param", "proxies", ":", "代理", ":", ...
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/net/requestslib.py#L125-L143
shi-cong/PYSTUDY
PYSTUDY/net/requestslib.py
HTTP.get_img
def get_img(self, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True, params=None): """ get方式获取 img 二进制信息 :param url: 访问Url :param headers: 请求头 :param cookies: 请求cookies :param timeout: 超时时间 :param verify:...
python
def get_img(self, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True, params=None): """ get方式获取 img 二进制信息 :param url: 访问Url :param headers: 请求头 :param cookies: 请求cookies :param timeout: 超时时间 :param verify:...
[ "def", "get_img", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "timeout", "=", "60", ",", "verify", "=", "False", ",", "proxies", "=", "None", ",", "allow_redirects", "=", "True", ",", "params", "=", "None",...
get方式获取 img 二进制信息 :param url: 访问Url :param headers: 请求头 :param cookies: 请求cookies :param timeout: 超时时间 :param verify: ssl验证 :param proxies: 代理 :param allow_redirects: 是否允许重定向 :param encoding: 返回的html编码s :param params: 查询请求参数 :return: 二进制图片数...
[ "get方式获取", "img", "二进制信息", ":", "param", "url", ":", "访问Url", ":", "param", "headers", ":", "请求头", ":", "param", "cookies", ":", "请求cookies", ":", "param", "timeout", ":", "超时时间", ":", "param", "verify", ":", "ssl验证", ":", "param", "proxies", ":", "代理"...
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/net/requestslib.py#L165-L187
openp2pdesign/makerlabs
makerlabs/repaircafe_org.py
data_from_repaircafe_org
def data_from_repaircafe_org(): """Gets data from repaircafe_org.""" # Use Chrome as a browser browser = webdriver.Chrome() # Use PhantomJS as a browser # browser = webdriver.PhantomJS('phantomjs') browser.get("https://repaircafe.org/en/?s=Contact+the+local+organisers") browser.maximize_win...
python
def data_from_repaircafe_org(): """Gets data from repaircafe_org.""" # Use Chrome as a browser browser = webdriver.Chrome() # Use PhantomJS as a browser # browser = webdriver.PhantomJS('phantomjs') browser.get("https://repaircafe.org/en/?s=Contact+the+local+organisers") browser.maximize_win...
[ "def", "data_from_repaircafe_org", "(", ")", ":", "# Use Chrome as a browser", "browser", "=", "webdriver", ".", "Chrome", "(", ")", "# Use PhantomJS as a browser", "# browser = webdriver.PhantomJS('phantomjs')", "browser", ".", "get", "(", "\"https://repaircafe.org/en/?s=Conta...
Gets data from repaircafe_org.
[ "Gets", "data", "from", "repaircafe_org", "." ]
train
https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/repaircafe_org.py#L44-L79
openp2pdesign/makerlabs
makerlabs/repaircafe_org.py
get_labs
def get_labs(format): """Gets Repair Cafe data from repairecafe.org.""" data = data_from_repaircafe_org() repaircafes = {} # Load all the Repair Cafes for i in data: # Create a lab current_lab = RepairCafe() # Add existing data from first scraping current_lab.name ...
python
def get_labs(format): """Gets Repair Cafe data from repairecafe.org.""" data = data_from_repaircafe_org() repaircafes = {} # Load all the Repair Cafes for i in data: # Create a lab current_lab = RepairCafe() # Add existing data from first scraping current_lab.name ...
[ "def", "get_labs", "(", "format", ")", ":", "data", "=", "data_from_repaircafe_org", "(", ")", "repaircafes", "=", "{", "}", "# Load all the Repair Cafes", "for", "i", "in", "data", ":", "# Create a lab", "current_lab", "=", "RepairCafe", "(", ")", "# Add existi...
Gets Repair Cafe data from repairecafe.org.
[ "Gets", "Repair", "Cafe", "data", "from", "repairecafe", ".", "org", "." ]
train
https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/repaircafe_org.py#L82-L214
aquatix/python-utilkit
utilkit/fileutil.py
archive_if_exists
def archive_if_exists(filename): """ Move `filename` out of the way, archiving it by appending the current datetime Can be a file or a directory """ if os.path.exists(filename): current_time = datetime.datetime.now() dt_format = '%Y-%m-%dT%H:%M:%S%z' timestamp = current_time....
python
def archive_if_exists(filename): """ Move `filename` out of the way, archiving it by appending the current datetime Can be a file or a directory """ if os.path.exists(filename): current_time = datetime.datetime.now() dt_format = '%Y-%m-%dT%H:%M:%S%z' timestamp = current_time....
[ "def", "archive_if_exists", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "current_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "dt_format", "=", "'%Y-%m-%dT%H:%M:%S%z'", "timestamp", "=", "...
Move `filename` out of the way, archiving it by appending the current datetime Can be a file or a directory
[ "Move", "filename", "out", "of", "the", "way", "archiving", "it", "by", "appending", "the", "current", "datetime", "Can", "be", "a", "file", "or", "a", "directory" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/fileutil.py#L45-L55
aquatix/python-utilkit
utilkit/fileutil.py
ensure_dir_exists
def ensure_dir_exists(f, fullpath=False): """ Ensure the existence of the (parent) directory of f """ if fullpath is False: # Get parent directory d = os.path.dirname(f) else: # Create the full path d = f if not os.path.exists(d): os.makedirs(d)
python
def ensure_dir_exists(f, fullpath=False): """ Ensure the existence of the (parent) directory of f """ if fullpath is False: # Get parent directory d = os.path.dirname(f) else: # Create the full path d = f if not os.path.exists(d): os.makedirs(d)
[ "def", "ensure_dir_exists", "(", "f", ",", "fullpath", "=", "False", ")", ":", "if", "fullpath", "is", "False", ":", "# Get parent directory", "d", "=", "os", ".", "path", ".", "dirname", "(", "f", ")", "else", ":", "# Create the full path", "d", "=", "f...
Ensure the existence of the (parent) directory of f
[ "Ensure", "the", "existence", "of", "the", "(", "parent", ")", "directory", "of", "f" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/fileutil.py#L58-L69
aquatix/python-utilkit
utilkit/fileutil.py
list_files
def list_files(dirname, extension=None): """ List all files in directory `dirname`, option to filter on file extension """ f = [] for (dirpath, dirnames, filenames) in os.walk(dirname): f.extend(filenames) break if extension is not None: # Filter on extension filt...
python
def list_files(dirname, extension=None): """ List all files in directory `dirname`, option to filter on file extension """ f = [] for (dirpath, dirnames, filenames) in os.walk(dirname): f.extend(filenames) break if extension is not None: # Filter on extension filt...
[ "def", "list_files", "(", "dirname", ",", "extension", "=", "None", ")", ":", "f", "=", "[", "]", "for", "(", "dirpath", ",", "dirnames", ",", "filenames", ")", "in", "os", ".", "walk", "(", "dirname", ")", ":", "f", ".", "extend", "(", "filenames"...
List all files in directory `dirname`, option to filter on file extension
[ "List", "all", "files", "in", "directory", "dirname", "option", "to", "filter", "on", "file", "extension" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/fileutil.py#L72-L88
aquatix/python-utilkit
utilkit/fileutil.py
filename_addstring
def filename_addstring(filename, text): """ Add `text` to filename, keeping the extension in place For example when adding a timestamp to the filename """ fn, ext = os.path.splitext(filename) return fn + text + ext
python
def filename_addstring(filename, text): """ Add `text` to filename, keeping the extension in place For example when adding a timestamp to the filename """ fn, ext = os.path.splitext(filename) return fn + text + ext
[ "def", "filename_addstring", "(", "filename", ",", "text", ")", ":", "fn", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "return", "fn", "+", "text", "+", "ext" ]
Add `text` to filename, keeping the extension in place For example when adding a timestamp to the filename
[ "Add", "text", "to", "filename", "keeping", "the", "extension", "in", "place", "For", "example", "when", "adding", "a", "timestamp", "to", "the", "filename" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/fileutil.py#L91-L97
aquatix/python-utilkit
utilkit/fileutil.py
get_file_contents
def get_file_contents(filename): """ Read file contents from file `filename` """ data = None try: with open(filename) as pf: data = pf.read() except IOError: # File not found, return None pass return data
python
def get_file_contents(filename): """ Read file contents from file `filename` """ data = None try: with open(filename) as pf: data = pf.read() except IOError: # File not found, return None pass return data
[ "def", "get_file_contents", "(", "filename", ")", ":", "data", "=", "None", "try", ":", "with", "open", "(", "filename", ")", "as", "pf", ":", "data", "=", "pf", ".", "read", "(", ")", "except", "IOError", ":", "# File not found, return None", "pass", "r...
Read file contents from file `filename`
[ "Read", "file", "contents", "from", "file", "filename" ]
train
https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/fileutil.py#L100-L111
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.parse_name
def parse_name(cls, name): """ Parses a name into a dictionary of identified subsections with accompanying information to correctly identify and replace if necessary :param name: str, string to be parsed :return: dict, dictionary with relevant parsed information """ ...
python
def parse_name(cls, name): """ Parses a name into a dictionary of identified subsections with accompanying information to correctly identify and replace if necessary :param name: str, string to be parsed :return: dict, dictionary with relevant parsed information """ ...
[ "def", "parse_name", "(", "cls", ",", "name", ")", ":", "parse_dict", "=", "dict", ".", "fromkeys", "(", "cls", ".", "PARSABLE", ",", "None", ")", "parse_dict", "[", "'date'", "]", "=", "cls", ".", "get_date", "(", "name", ")", "parse_dict", "[", "'v...
Parses a name into a dictionary of identified subsections with accompanying information to correctly identify and replace if necessary :param name: str, string to be parsed :return: dict, dictionary with relevant parsed information
[ "Parses", "a", "name", "into", "a", "dictionary", "of", "identified", "subsections", "with", "accompanying", "information", "to", "correctly", "identify", "and", "replace", "if", "necessary" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L35-L48
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_side
def get_side(cls, name, ignore=''): """ Checks a string for a possible side string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found side to reduce duplicates. We can be safe to assume the abbreviation for the side does no...
python
def get_side(cls, name, ignore=''): """ Checks a string for a possible side string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found side to reduce duplicates. We can be safe to assume the abbreviation for the side does no...
[ "def", "get_side", "(", "cls", ",", "name", ",", "ignore", "=", "''", ")", ":", "for", "side", "in", "cls", ".", "CONFIG_SIDES", ":", "\"\"\" Tried using a regex, however it would've taken too long to debug\n side_regex = cls._build_abbreviation_regex(side)\n ...
Checks a string for a possible side string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found side to reduce duplicates. We can be safe to assume the abbreviation for the side does not have camel casing within its own word. ...
[ "Checks", "a", "string", "for", "a", "possible", "side", "string", "token", "this", "assumes", "its", "on", "its", "own", "and", "is", "not", "part", "of", "or", "camel", "cased", "and", "combined", "with", "a", "word", ".", "Returns", "first", "found", ...
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L51-L72
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_discipline
def get_discipline(cls, name, ignore='', min_length=3): """ Checks a string for a possible discipline string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found match to reduce duplicates. We can be safe to assume the abbrev...
python
def get_discipline(cls, name, ignore='', min_length=3): """ Checks a string for a possible discipline string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found match to reduce duplicates. We can be safe to assume the abbrev...
[ "def", "get_discipline", "(", "cls", ",", "name", ",", "ignore", "=", "''", ",", "min_length", "=", "3", ")", ":", "for", "discipline", "in", "cls", ".", "CONFIG_DISCIPLINES", ":", "re_abbr", "=", "'({RECURSE}(?=[0-9]|[A-Z]|{SEPARATORS}))'", ".", "format", "("...
Checks a string for a possible discipline string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found match to reduce duplicates. We can be safe to assume the abbreviation for the discipline does not have camel casing within its own ...
[ "Checks", "a", "string", "for", "a", "possible", "discipline", "string", "token", "this", "assumes", "its", "on", "its", "own", "and", "is", "not", "part", "of", "or", "camel", "cased", "and", "combined", "with", "a", "word", ".", "Returns", "first", "fo...
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L75-L95
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_base_naive
def get_base_naive(cls, name, ignore=''): """ Checks a string for a possible base name of an object (no prefix, no suffix). We need to do a full parse to make sure we've ruled out all the possible other parse queries :param name: str, string that represents a possible name of an object ...
python
def get_base_naive(cls, name, ignore=''): """ Checks a string for a possible base name of an object (no prefix, no suffix). We need to do a full parse to make sure we've ruled out all the possible other parse queries :param name: str, string that represents a possible name of an object ...
[ "def", "get_base_naive", "(", "cls", ",", "name", ",", "ignore", "=", "''", ")", ":", "return", "cls", ".", "_get_regex_search", "(", "name", ",", "cls", ".", "REGEX_BASENAME", ",", "match_index", "=", "0", ",", "ignore", "=", "ignore", ")" ]
Checks a string for a possible base name of an object (no prefix, no suffix). We need to do a full parse to make sure we've ruled out all the possible other parse queries :param name: str, string that represents a possible name of an object :return: str, the detected basename
[ "Checks", "a", "string", "for", "a", "possible", "base", "name", "of", "an", "object", "(", "no", "prefix", "no", "suffix", ")", ".", "We", "need", "to", "do", "a", "full", "parse", "to", "make", "sure", "we", "ve", "ruled", "out", "all", "the", "p...
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L108-L115
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_version
def get_version(cls, name): """ Checks a string for a possible version of an object (no prefix, no suffix). Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), gets the version number then t...
python
def get_version(cls, name): """ Checks a string for a possible version of an object (no prefix, no suffix). Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), gets the version number then t...
[ "def", "get_version", "(", "cls", ",", "name", ")", ":", "# Dates can confuse th", "# is stuff, so we'll check for that first and remove it from the string if found", "try", ":", "date", "=", "cls", ".", "get_date", "(", "name", ")", "date", "=", "date", "[", "'dateti...
Checks a string for a possible version of an object (no prefix, no suffix). Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), gets the version number then the string matches
[ "Checks", "a", "string", "for", "a", "possible", "version", "of", "an", "object", "(", "no", "prefix", "no", "suffix", ")", ".", "Assumes", "only", "up", "to", "4", "digit", "padding" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L118-L132
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_version_naive
def get_version_naive(cls, name, ignore=''): """ Checks a string for a possible version of an object (no prefix, no suffix) without filtering date out Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(...
python
def get_version_naive(cls, name, ignore=''): """ Checks a string for a possible version of an object (no prefix, no suffix) without filtering date out Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(...
[ "def", "get_version_naive", "(", "cls", ",", "name", ",", "ignore", "=", "''", ")", ":", "match", "=", "cls", ".", "_get_regex_search", "(", "name", ",", "cls", ".", "REGEX_VERSION", ".", "format", "(", "SEP", "=", "cls", ".", "REGEX_SEPARATORS", ")", ...
Checks a string for a possible version of an object (no prefix, no suffix) without filtering date out Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), gets the version number then the string matc...
[ "Checks", "a", "string", "for", "a", "possible", "version", "of", "an", "object", "(", "no", "prefix", "no", "suffix", ")", "without", "filtering", "date", "out", "Assumes", "only", "up", "to", "4", "digit", "padding" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L135-L160
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_udim
def get_udim(cls, name): """ Checks a string for a possible base name of an object (no prefix, no suffix) :param name: str, string that represents a possible name of an object :returns: int, the last found match because convention keeps UDIM markers at the end. """ match = cls._...
python
def get_udim(cls, name): """ Checks a string for a possible base name of an object (no prefix, no suffix) :param name: str, string that represents a possible name of an object :returns: int, the last found match because convention keeps UDIM markers at the end. """ match = cls._...
[ "def", "get_udim", "(", "cls", ",", "name", ")", ":", "match", "=", "cls", ".", "_get_regex_search", "(", "name", ",", "cls", ".", "REGEX_UDIM", ",", "match_index", "=", "-", "1", ")", "if", "match", ":", "match", ".", "update", "(", "{", "'match_int...
Checks a string for a possible base name of an object (no prefix, no suffix) :param name: str, string that represents a possible name of an object :returns: int, the last found match because convention keeps UDIM markers at the end.
[ "Checks", "a", "string", "for", "a", "possible", "base", "name", "of", "an", "object", "(", "no", "prefix", "no", "suffix", ")" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L163-L173
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_date
def get_date(cls, name): """ Checks a string for a possible date formatted into the name. It assumes dates do not have other numbers at the front or head of the date. Currently only supports dates in 1900 and 2000. Heavily relies on datetime for error checking to see if dat...
python
def get_date(cls, name): """ Checks a string for a possible date formatted into the name. It assumes dates do not have other numbers at the front or head of the date. Currently only supports dates in 1900 and 2000. Heavily relies on datetime for error checking to see if dat...
[ "def", "get_date", "(", "cls", ",", "name", ")", ":", "time_formats", "=", "[", "'%Y-%m-%d_%H-%M-%S'", ",", "'%Y-%m-%d-%H-%M-%S'", ",", "'%Y-%m-%d--%H-%M-%S'", ",", "'%y_%m_%dT%H_%M_%S'", ",", "'%Y-%m-%d%H-%M-%S'", ",", "'%Y%m%d-%H%M%S'", ",", "'%Y%m%d-%H%M'", ",", ...
Checks a string for a possible date formatted into the name. It assumes dates do not have other numbers at the front or head of the date. Currently only supports dates in 1900 and 2000. Heavily relies on datetime for error checking to see if date is actually viable. It follows simi...
[ "Checks", "a", "string", "for", "a", "possible", "date", "formatted", "into", "the", "name", ".", "It", "assumes", "dates", "do", "not", "have", "other", "numbers", "at", "the", "front", "or", "head", "of", "the", "date", ".", "Currently", "only", "suppo...
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L185-L235
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.get_string_camel_patterns
def get_string_camel_patterns(cls, name, min_length=0): """ Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :retur...
python
def get_string_camel_patterns(cls, name, min_length=0): """ Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :retur...
[ "def", "get_string_camel_patterns", "(", "cls", ",", "name", ",", "min_length", "=", "0", ")", ":", "# Have to check for longest first and remove duplicates", "patterns", "=", "[", "]", "abbreviations", "=", "list", "(", "set", "(", "cls", ".", "_get_abbreviations",...
Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :return: list(list(str)), list casing permutations of list of abbreviation...
[ "Finds", "all", "permutations", "of", "possible", "camel", "casing", "of", "the", "given", "name" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L238-L261
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser._reduce_name
def _reduce_name(cls, name, parse_dict): """ Reduces a name against matches found in a parse dictionary :param name: str, name to be reduced :param parse_dict: dict, dictionary of matches to reduce against :return: str, reduced string """ # Now remove all found entries t...
python
def _reduce_name(cls, name, parse_dict): """ Reduces a name against matches found in a parse dictionary :param name: str, name to be reduced :param parse_dict: dict, dictionary of matches to reduce against :return: str, reduced string """ # Now remove all found entries t...
[ "def", "_reduce_name", "(", "cls", ",", "name", ",", "parse_dict", ")", ":", "# Now remove all found entries to make basename regex have an easier time", "removal_indices", "=", "[", "]", "for", "section", ",", "match", "in", "iteritems", "(", "parse_dict", ")", ":", ...
Reduces a name against matches found in a parse dictionary :param name: str, name to be reduced :param parse_dict: dict, dictionary of matches to reduce against :return: str, reduced string
[ "Reduces", "a", "name", "against", "matches", "found", "in", "a", "parse", "dictionary" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L264-L301
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser._get_regex_search
def _get_regex_search(input_string, regex, metadata={}, match_index=None, ignore='', flags=0): """ Using this so that all results from the functions return similar results :param input_string: str, input string to be checked :param regex: str, input regex to be compiled and searched with ...
python
def _get_regex_search(input_string, regex, metadata={}, match_index=None, ignore='', flags=0): """ Using this so that all results from the functions return similar results :param input_string: str, input string to be checked :param regex: str, input regex to be compiled and searched with ...
[ "def", "_get_regex_search", "(", "input_string", ",", "regex", ",", "metadata", "=", "{", "}", ",", "match_index", "=", "None", ",", "ignore", "=", "''", ",", "flags", "=", "0", ")", ":", "generator", "=", "re", ".", "compile", "(", "regex", ",", "fl...
Using this so that all results from the functions return similar results :param input_string: str, input string to be checked :param regex: str, input regex to be compiled and searched with :param match_index: (int, None), whether to get a specific match, if None returns all matches as list ...
[ "Using", "this", "so", "that", "all", "results", "from", "the", "functions", "return", "similar", "results" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L304-L341
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser._generic_search
def _generic_search(cls, name, search_string, metadata={}, ignore=''): """ Searches for a specific string given three types of regex search types. Also auto-checks for camel casing. :param name: str, name of object in question :param search_string: str, string to find and insert into the searc...
python
def _generic_search(cls, name, search_string, metadata={}, ignore=''): """ Searches for a specific string given three types of regex search types. Also auto-checks for camel casing. :param name: str, name of object in question :param search_string: str, string to find and insert into the searc...
[ "def", "_generic_search", "(", "cls", ",", "name", ",", "search_string", ",", "metadata", "=", "{", "}", ",", "ignore", "=", "''", ")", ":", "patterns", "=", "[", "cls", ".", "REGEX_ABBR_SEOS", ",", "cls", ".", "REGEX_ABBR_ISLAND", ",", "cls", ".", "RE...
Searches for a specific string given three types of regex search types. Also auto-checks for camel casing. :param name: str, name of object in question :param search_string: str, string to find and insert into the search regexes :param metadata: dict, metadata to add to the result if we find a...
[ "Searches", "for", "a", "specific", "string", "given", "three", "types", "of", "regex", "search", "types", ".", "Also", "auto", "-", "checks", "for", "camel", "casing", "." ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L344-L369
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser._get_abbreviations
def _get_abbreviations(input_string, output_length=0): """ Generates abbreviations for input_string :param input_string: str, name of object :param output_length: int, optional specific length of abbreviations, default is off :return: list(str), list of all combinations that include the...
python
def _get_abbreviations(input_string, output_length=0): """ Generates abbreviations for input_string :param input_string: str, name of object :param output_length: int, optional specific length of abbreviations, default is off :return: list(str), list of all combinations that include the...
[ "def", "_get_abbreviations", "(", "input_string", ",", "output_length", "=", "0", ")", ":", "for", "i", ",", "j", "in", "itertools", ".", "combinations", "(", "range", "(", "len", "(", "input_string", "[", "1", ":", "]", ")", "+", "1", ")", ",", "2",...
Generates abbreviations for input_string :param input_string: str, name of object :param output_length: int, optional specific length of abbreviations, default is off :return: list(str), list of all combinations that include the first letter (possible abbreviations)
[ "Generates", "abbreviations", "for", "input_string" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L372-L387
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser.is_valid_camel
def is_valid_camel(cls, input_string, strcmp=None, ignore=''): """ Checks to see if an input string is valid for use in camel casing This assumes that all lowercase strings are not valid camel case situations and no camel string can just be a capitalized word. Took ideas from here: ...
python
def is_valid_camel(cls, input_string, strcmp=None, ignore=''): """ Checks to see if an input string is valid for use in camel casing This assumes that all lowercase strings are not valid camel case situations and no camel string can just be a capitalized word. Took ideas from here: ...
[ "def", "is_valid_camel", "(", "cls", ",", "input_string", ",", "strcmp", "=", "None", ",", "ignore", "=", "''", ")", ":", "# clear any non chars from the string", "if", "not", "input_string", ":", "return", "False", "input_string", "=", "''", ".", "join", "(",...
Checks to see if an input string is valid for use in camel casing This assumes that all lowercase strings are not valid camel case situations and no camel string can just be a capitalized word. Took ideas from here: http://stackoverflow.com/questions/29916065/how-to-do-camelcase-spl...
[ "Checks", "to", "see", "if", "an", "input", "string", "is", "valid", "for", "use", "in", "camel", "casing", "This", "assumes", "that", "all", "lowercase", "strings", "are", "not", "valid", "camel", "case", "situations", "and", "no", "camel", "string", "can...
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L390-L421
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser._get_casing_permutations
def _get_casing_permutations(cls, input_string): """ Takes a string and gives all possible permutations of casing for comparative purposes :param input_string: str, name of object :return: Generator(str), iterator of all possible permutations of casing for the input_string """ i...
python
def _get_casing_permutations(cls, input_string): """ Takes a string and gives all possible permutations of casing for comparative purposes :param input_string: str, name of object :return: Generator(str), iterator of all possible permutations of casing for the input_string """ i...
[ "def", "_get_casing_permutations", "(", "cls", ",", "input_string", ")", ":", "if", "not", "input_string", ":", "yield", "\"\"", "else", ":", "first", "=", "input_string", "[", ":", "1", "]", "for", "sub_casing", "in", "cls", ".", "_get_casing_permutations", ...
Takes a string and gives all possible permutations of casing for comparative purposes :param input_string: str, name of object :return: Generator(str), iterator of all possible permutations of casing for the input_string
[ "Takes", "a", "string", "and", "gives", "all", "possible", "permutations", "of", "casing", "for", "comparative", "purposes" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L433-L445
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser._string_remove_slice
def _string_remove_slice(input_str, start, end): """ Removes portions of a string :param input_str: str, input string :param start: int, end search index :param end: int, start search index :return: str, the cut string """ if 0 <= start < end <= len(input_str): ...
python
def _string_remove_slice(input_str, start, end): """ Removes portions of a string :param input_str: str, input string :param start: int, end search index :param end: int, start search index :return: str, the cut string """ if 0 <= start < end <= len(input_str): ...
[ "def", "_string_remove_slice", "(", "input_str", ",", "start", ",", "end", ")", ":", "if", "0", "<=", "start", "<", "end", "<=", "len", "(", "input_str", ")", ":", "return", "input_str", "[", ":", "start", "]", "+", "input_str", "[", "end", ":", "]",...
Removes portions of a string :param input_str: str, input string :param start: int, end search index :param end: int, start search index :return: str, the cut string
[ "Removes", "portions", "of", "a", "string" ]
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L448-L458
AndresMWeber/Nomenclate
nomenclate/core/nameparser.py
NameParser._build_abbreviation_regex
def _build_abbreviation_regex(input_string): """ builds a recursive regex based on an input string to find possible abbreviations more simply. e.g. = punct(u(a(t(i(on?)?)?)?)?)? :param input_string: str, input string :return: str, output regex """ result='' f...
python
def _build_abbreviation_regex(input_string): """ builds a recursive regex based on an input string to find possible abbreviations more simply. e.g. = punct(u(a(t(i(on?)?)?)?)?)? :param input_string: str, input string :return: str, output regex """ result='' f...
[ "def", "_build_abbreviation_regex", "(", "input_string", ")", ":", "result", "=", "''", "for", "char", "in", "input_string", ":", "result", "+=", "'[%s%s]?'", "%", "(", "char", ".", "upper", "(", ")", ",", "char", ".", "lower", "(", ")", ")", "return", ...
builds a recursive regex based on an input string to find possible abbreviations more simply. e.g. = punct(u(a(t(i(on?)?)?)?)?)? :param input_string: str, input string :return: str, output regex
[ "builds", "a", "recursive", "regex", "based", "on", "an", "input", "string", "to", "find", "possible", "abbreviations", "more", "simply", ".", "e", ".", "g", ".", "=", "punct", "(", "u", "(", "a", "(", "t", "(", "i", "(", "on?", ")", "?", ")", "?...
train
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L461-L471
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/executables/gitlab_set_variables.py
_parse_args
def _parse_args(args: List[str]) -> _SetArgumentsRunConfig: """ Parses the given CLI arguments to get a run configuration. :param args: CLI arguments :return: run configuration derived from the given CLI arguments """ parser = argparse.ArgumentParser( prog="gitlab-set-variables", descrip...
python
def _parse_args(args: List[str]) -> _SetArgumentsRunConfig: """ Parses the given CLI arguments to get a run configuration. :param args: CLI arguments :return: run configuration derived from the given CLI arguments """ parser = argparse.ArgumentParser( prog="gitlab-set-variables", descrip...
[ "def", "_parse_args", "(", "args", ":", "List", "[", "str", "]", ")", "->", "_SetArgumentsRunConfig", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"gitlab-set-variables\"", ",", "description", "=", "\"Tool for setting a GitLab project's...
Parses the given CLI arguments to get a run configuration. :param args: CLI arguments :return: run configuration derived from the given CLI arguments
[ "Parses", "the", "given", "CLI", "arguments", "to", "get", "a", "run", "configuration", ".", ":", "param", "args", ":", "CLI", "arguments", ":", "return", ":", "run", "configuration", "derived", "from", "the", "given", "CLI", "arguments" ]
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_set_variables.py#L21-L35
wtsi-hgi/gitlab-build-variables
gitlabbuildvariables/executables/gitlab_set_variables.py
main
def main(): """ Main method. """ run_config = _parse_args(sys.argv[1:]) gitlab_config = GitLabConfig(run_config.url, run_config.token) manager = ProjectVariablesManager(gitlab_config, run_config.project) variables = {} # type: Dict[str, str] for source in run_config.source: vari...
python
def main(): """ Main method. """ run_config = _parse_args(sys.argv[1:]) gitlab_config = GitLabConfig(run_config.url, run_config.token) manager = ProjectVariablesManager(gitlab_config, run_config.project) variables = {} # type: Dict[str, str] for source in run_config.source: vari...
[ "def", "main", "(", ")", ":", "run_config", "=", "_parse_args", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "gitlab_config", "=", "GitLabConfig", "(", "run_config", ".", "url", ",", "run_config", ".", "token", ")", "manager", "=", "ProjectVariables...
Main method.
[ "Main", "method", "." ]
train
https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_set_variables.py#L38-L49
jpscaletti/moar
moar/engines/base.py
BaseEngine.set_geometry
def set_geometry(self, im, geometry, options=None): """Rescale the image to the new geometry. """ if not geometry: return im options = options or {} width, height = geometry if not width and not height: return im imw, imh = self.get_size(...
python
def set_geometry(self, im, geometry, options=None): """Rescale the image to the new geometry. """ if not geometry: return im options = options or {} width, height = geometry if not width and not height: return im imw, imh = self.get_size(...
[ "def", "set_geometry", "(", "self", ",", "im", ",", "geometry", ",", "options", "=", "None", ")", ":", "if", "not", "geometry", ":", "return", "im", "options", "=", "options", "or", "{", "}", "width", ",", "height", "=", "geometry", "if", "not", "wid...
Rescale the image to the new geometry.
[ "Rescale", "the", "image", "to", "the", "new", "geometry", "." ]
train
https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/engines/base.py#L36-L97
unfoldingWord-dev/tx-shared-tools
general_tools/url_utils.py
get_url
def get_url(url, catch_exception=False): """ :param str|unicode url: URL to open :param bool catch_exception: If <True> catches all exceptions and returns <False> """ return _get_url(url, catch_exception, urlopen=urllib2.urlopen)
python
def get_url(url, catch_exception=False): """ :param str|unicode url: URL to open :param bool catch_exception: If <True> catches all exceptions and returns <False> """ return _get_url(url, catch_exception, urlopen=urllib2.urlopen)
[ "def", "get_url", "(", "url", ",", "catch_exception", "=", "False", ")", ":", "return", "_get_url", "(", "url", ",", "catch_exception", ",", "urlopen", "=", "urllib2", ".", "urlopen", ")" ]
:param str|unicode url: URL to open :param bool catch_exception: If <True> catches all exceptions and returns <False>
[ ":", "param", "str|unicode", "url", ":", "URL", "to", "open", ":", "param", "bool", "catch_exception", ":", "If", "<True", ">", "catches", "all", "exceptions", "and", "returns", "<False", ">" ]
train
https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/url_utils.py#L13-L18
unfoldingWord-dev/tx-shared-tools
general_tools/url_utils.py
join_url_parts
def join_url_parts(*args): """ Joins a list of segments into a URL-like string :type args: List<string> """ # check for edge case if len(args) == 1: return args[0] return_val = clean_url_segment(args[0]) for i in range(1, len(args)): arg = args[i] if i == len(a...
python
def join_url_parts(*args): """ Joins a list of segments into a URL-like string :type args: List<string> """ # check for edge case if len(args) == 1: return args[0] return_val = clean_url_segment(args[0]) for i in range(1, len(args)): arg = args[i] if i == len(a...
[ "def", "join_url_parts", "(", "*", "args", ")", ":", "# check for edge case", "if", "len", "(", "args", ")", "==", "1", ":", "return", "args", "[", "0", "]", "return_val", "=", "clean_url_segment", "(", "args", "[", "0", "]", ")", "for", "i", "in", "...
Joins a list of segments into a URL-like string :type args: List<string>
[ "Joins", "a", "list", "of", "segments", "into", "a", "URL", "-", "like", "string", ":", "type", "args", ":", "List<string", ">" ]
train
https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/url_utils.py#L83-L104
noobermin/lspreader
lspreader/flds.py
getvector
def getvector(d,s): ''' Get a vector flds data. Parameters: ----------- d -- flds data. s -- key for the data. ''' return np.array([d[s+"x"],d[s+"y"],d[s+"z"]]);
python
def getvector(d,s): ''' Get a vector flds data. Parameters: ----------- d -- flds data. s -- key for the data. ''' return np.array([d[s+"x"],d[s+"y"],d[s+"z"]]);
[ "def", "getvector", "(", "d", ",", "s", ")", ":", "return", "np", ".", "array", "(", "[", "d", "[", "s", "+", "\"x\"", "]", ",", "d", "[", "s", "+", "\"y\"", "]", ",", "d", "[", "s", "+", "\"z\"", "]", "]", ")" ]
Get a vector flds data. Parameters: ----------- d -- flds data. s -- key for the data.
[ "Get", "a", "vector", "flds", "data", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/flds.py#L11-L21
noobermin/lspreader
lspreader/flds.py
read_indexed
def read_indexed(i,flds=None,sclr=None, gzip='guess', dir='.', vector_norms=True, keep_xs=False,gettime=False): ''' A smart indexing reader that reads files by names. Looks for files like "<dir>/flds<i>.p4<compression>" where dir and the index are passed, as well as stu...
python
def read_indexed(i,flds=None,sclr=None, gzip='guess', dir='.', vector_norms=True, keep_xs=False,gettime=False): ''' A smart indexing reader that reads files by names. Looks for files like "<dir>/flds<i>.p4<compression>" where dir and the index are passed, as well as stu...
[ "def", "read_indexed", "(", "i", ",", "flds", "=", "None", ",", "sclr", "=", "None", ",", "gzip", "=", "'guess'", ",", "dir", "=", "'.'", ",", "vector_norms", "=", "True", ",", "keep_xs", "=", "False", ",", "gettime", "=", "False", ")", ":", "fldsp...
A smart indexing reader that reads files by names. Looks for files like "<dir>/flds<i>.p4<compression>" where dir and the index are passed, as well as stuff from sclrs and saves them into one dictionary. Essentially useful for reading by timestep instead of by file. Assumes that both the flds and sclr a...
[ "A", "smart", "indexing", "reader", "that", "reads", "files", "by", "names", ".", "Looks", "for", "files", "like", "<dir", ">", "/", "flds<i", ">", ".", "p4<compression", ">", "where", "dir", "and", "the", "index", "are", "passed", "as", "well", "as", ...
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/flds.py#L35-L108
noobermin/lspreader
lspreader/flds.py
restrict
def restrict(d,restrict): ''' Restrict data by indices. Parameters: ---------- d -- the flds/sclr data restrict -- a tuple of [xmin,xmax,...] etx ''' notqs = ['t','xs','ys','zs','fd','sd'] keys = [k for k in d if k not in notqs]; if len(restrict) == 2: for k i...
python
def restrict(d,restrict): ''' Restrict data by indices. Parameters: ---------- d -- the flds/sclr data restrict -- a tuple of [xmin,xmax,...] etx ''' notqs = ['t','xs','ys','zs','fd','sd'] keys = [k for k in d if k not in notqs]; if len(restrict) == 2: for k i...
[ "def", "restrict", "(", "d", ",", "restrict", ")", ":", "notqs", "=", "[", "'t'", ",", "'xs'", ",", "'ys'", ",", "'zs'", ",", "'fd'", ",", "'sd'", "]", "keys", "=", "[", "k", "for", "k", "in", "d", "if", "k", "not", "in", "notqs", "]", "if", ...
Restrict data by indices. Parameters: ---------- d -- the flds/sclr data restrict -- a tuple of [xmin,xmax,...] etx
[ "Restrict", "data", "by", "indices", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/flds.py#L110-L140
pztrick/DjScript
djscript/templatetags/djscript.py
djurl
def djurl(dot_path): """ DEBUG == True ? Compiles and serves file at dot_path DEBUG == False ? Serves pre-compiled file path Usage: {% djurl 'path.to.file' %} """ try: http_path = os.path.join(getattr(settings, 'STATIC_URL', ''), djurls[dot_path]) if settings.D...
python
def djurl(dot_path): """ DEBUG == True ? Compiles and serves file at dot_path DEBUG == False ? Serves pre-compiled file path Usage: {% djurl 'path.to.file' %} """ try: http_path = os.path.join(getattr(settings, 'STATIC_URL', ''), djurls[dot_path]) if settings.D...
[ "def", "djurl", "(", "dot_path", ")", ":", "try", ":", "http_path", "=", "os", ".", "path", ".", "join", "(", "getattr", "(", "settings", ",", "'STATIC_URL'", ",", "''", ")", ",", "djurls", "[", "dot_path", "]", ")", "if", "settings", ".", "DEBUG", ...
DEBUG == True ? Compiles and serves file at dot_path DEBUG == False ? Serves pre-compiled file path Usage: {% djurl 'path.to.file' %}
[ "DEBUG", "==", "True", "?", "Compiles", "and", "serves", "file", "at", "dot_path", "DEBUG", "==", "False", "?", "Serves", "pre", "-", "compiled", "file", "path", "Usage", ":", "{", "%", "djurl", "path", ".", "to", ".", "file", "%", "}" ]
train
https://github.com/pztrick/DjScript/blob/a1fc3b975e7ba7015ef3e5d3d69e02d69b7c1d24/djscript/templatetags/djscript.py#L20-L55
mdeous/fatbotslim
fatbotslim/log.py
create_logger
def create_logger(name, level='INFO'): """ Creates a new ready-to-use logger. :param name: new logger's name :type name: str :param level: default logging level. :type level: :class:`str` or :class:`int` :return: new logger. :rtype: :class:`logging.Logger` """ formatter = ColorF...
python
def create_logger(name, level='INFO'): """ Creates a new ready-to-use logger. :param name: new logger's name :type name: str :param level: default logging level. :type level: :class:`str` or :class:`int` :return: new logger. :rtype: :class:`logging.Logger` """ formatter = ColorF...
[ "def", "create_logger", "(", "name", ",", "level", "=", "'INFO'", ")", ":", "formatter", "=", "ColorFormatter", "(", "LOG_FORMAT", ",", "DATE_FORMAT", ")", "if", "not", "isinstance", "(", "logging", ".", "getLevelName", "(", "level", ")", ",", "int", ")", ...
Creates a new ready-to-use logger. :param name: new logger's name :type name: str :param level: default logging level. :type level: :class:`str` or :class:`int` :return: new logger. :rtype: :class:`logging.Logger`
[ "Creates", "a", "new", "ready", "-", "to", "-", "use", "logger", "." ]
train
https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/log.py#L65-L84
mdeous/fatbotslim
fatbotslim/log.py
ColorFormatter.format
def format(self, record): """ Overrides the default :func:`logging.Formatter.format` to add colors to the :obj:`record`'s :attr:`levelname` and :attr:`name` attributes. """ level_length = len(record.levelname) if record.levelname in self._colors_map: record.ms...
python
def format(self, record): """ Overrides the default :func:`logging.Formatter.format` to add colors to the :obj:`record`'s :attr:`levelname` and :attr:`name` attributes. """ level_length = len(record.levelname) if record.levelname in self._colors_map: record.ms...
[ "def", "format", "(", "self", ",", "record", ")", ":", "level_length", "=", "len", "(", "record", ".", "levelname", ")", "if", "record", ".", "levelname", "in", "self", ".", "_colors_map", ":", "record", ".", "msg", "=", "'{0}{1}\\033[0;0m'", ".", "forma...
Overrides the default :func:`logging.Formatter.format` to add colors to the :obj:`record`'s :attr:`levelname` and :attr:`name` attributes.
[ "Overrides", "the", "default", ":", "func", ":", "logging", ".", "Formatter", ".", "format", "to", "add", "colors", "to", "the", ":", "obj", ":", "record", "s", ":", "attr", ":", "levelname", "and", ":", "attr", ":", "name", "attributes", "." ]
train
https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/log.py#L45-L62
HazardDede/dictmentor
dictmentor/validator.py
Validator.instance_of
def instance_of(target_type: Optional[type] = None, raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given key-value pairs (items) are instances of the given ``target_type``. Per default this function yields whether ``True`` or...
python
def instance_of(target_type: Optional[type] = None, raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given key-value pairs (items) are instances of the given ``target_type``. Per default this function yields whether ``True`` or...
[ "def", "instance_of", "(", "target_type", ":", "Optional", "[", "type", "]", "=", "None", ",", "raise_ex", ":", "bool", "=", "False", ",", "summary", ":", "bool", "=", "True", ",", "*", "*", "items", ":", "Any", ")", "->", "ValidationReturn", ":", "i...
Tests if the given key-value pairs (items) are instances of the given ``target_type``. Per default this function yields whether ``True`` or ``False`` depending on the fact if all items withstand the validation or not. Per default the validation / evaluation is short-circuit and will return as so...
[ "Tests", "if", "the", "given", "key", "-", "value", "pairs", "(", "items", ")", "are", "instances", "of", "the", "given", "target_type", ".", "Per", "default", "this", "function", "yields", "whether", "True", "or", "False", "depending", "on", "the", "fact"...
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/validator.py#L77-L147
HazardDede/dictmentor
dictmentor/validator.py
Validator.is_stream
def is_stream(raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given key-value pairs (items) are all streams. Basically checks if the item provides a read(...) method. Per default this function yields whether ``True`` or ...
python
def is_stream(raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given key-value pairs (items) are all streams. Basically checks if the item provides a read(...) method. Per default this function yields whether ``True`` or ...
[ "def", "is_stream", "(", "raise_ex", ":", "bool", "=", "False", ",", "summary", ":", "bool", "=", "True", ",", "*", "*", "items", ":", "Any", ")", "->", "ValidationReturn", ":", "return", "Validator", ".", "__test_all", "(", "condition", "=", "lambda", ...
Tests if the given key-value pairs (items) are all streams. Basically checks if the item provides a read(...) method. Per default this function yields whether ``True`` or ``False`` depending on the fact if all items withstand the validation or not. Per default the validation / evaluation is ...
[ "Tests", "if", "the", "given", "key", "-", "value", "pairs", "(", "items", ")", "are", "all", "streams", ".", "Basically", "checks", "if", "the", "item", "provides", "a", "read", "(", "...", ")", "method", ".", "Per", "default", "this", "function", "yi...
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/validator.py#L150-L209
HazardDede/dictmentor
dictmentor/validator.py
Validator.is_file
def is_file(raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given key-value pairs (items) are physical existent files or links to regular files. Per default this function yields whether ``True`` or ``False`` depending on t...
python
def is_file(raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given key-value pairs (items) are physical existent files or links to regular files. Per default this function yields whether ``True`` or ``False`` depending on t...
[ "def", "is_file", "(", "raise_ex", ":", "bool", "=", "False", ",", "summary", ":", "bool", "=", "True", ",", "*", "*", "items", ":", "Any", ")", "->", "ValidationReturn", ":", "return", "Validator", ".", "__test_all", "(", "condition", "=", "lambda", "...
Tests if the given key-value pairs (items) are physical existent files or links to regular files. Per default this function yields whether ``True`` or ``False`` depending on the fact if all items withstand the validation or not. Per default the validation / evaluation is short-circuit an...
[ "Tests", "if", "the", "given", "key", "-", "value", "pairs", "(", "items", ")", "are", "physical", "existent", "files", "or", "links", "to", "regular", "files", ".", "Per", "default", "this", "function", "yields", "whether", "True", "or", "False", "dependi...
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/validator.py#L212-L275
HazardDede/dictmentor
dictmentor/validator.py
Validator.is_real_iterable
def is_real_iterable(raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given items are iterables (collections) but no strings. Per default this function yields whether ``True`` or ``False`` depending on the fact if all ...
python
def is_real_iterable(raise_ex: bool = False, summary: bool = True, **items: Any) -> ValidationReturn: """ Tests if the given items are iterables (collections) but no strings. Per default this function yields whether ``True`` or ``False`` depending on the fact if all ...
[ "def", "is_real_iterable", "(", "raise_ex", ":", "bool", "=", "False", ",", "summary", ":", "bool", "=", "True", ",", "*", "*", "items", ":", "Any", ")", "->", "ValidationReturn", ":", "return", "Validator", ".", "__test_all", "(", "condition", "=", "lam...
Tests if the given items are iterables (collections) but no strings. Per default this function yields whether ``True`` or ``False`` depending on the fact if all items withstand the validation or not. Per default the validation / evaluation is short-circuit and will return as soon an item evaluat...
[ "Tests", "if", "the", "given", "items", "are", "iterables", "(", "collections", ")", "but", "no", "strings", ".", "Per", "default", "this", "function", "yields", "whether", "True", "or", "False", "depending", "on", "the", "fact", "if", "all", "items", "wit...
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/validator.py#L278-L337
elifesciences/elife-article
elifearticle/parse.py
build_contributors
def build_contributors(authors, contrib_type, competing_interests=None): """ Given a list of authors from the parser, instantiate contributors objects and build them """ contributors = [] for author in authors: contributor = None author_contrib_type = contrib_type surn...
python
def build_contributors(authors, contrib_type, competing_interests=None): """ Given a list of authors from the parser, instantiate contributors objects and build them """ contributors = [] for author in authors: contributor = None author_contrib_type = contrib_type surn...
[ "def", "build_contributors", "(", "authors", ",", "contrib_type", ",", "competing_interests", "=", "None", ")", ":", "contributors", "=", "[", "]", "for", "author", "in", "authors", ":", "contributor", "=", "None", "author_contrib_type", "=", "contrib_type", "su...
Given a list of authors from the parser, instantiate contributors objects and build them
[ "Given", "a", "list", "of", "authors", "from", "the", "parser", "instantiate", "contributors", "objects", "and", "build", "them" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L16-L75
elifesciences/elife-article
elifearticle/parse.py
build_funding
def build_funding(award_groups): """ Given a funding data, format it """ if not award_groups: return [] funding_awards = [] for award_groups_item in award_groups: for award_group_id, award_group in iteritems(award_groups_item): award = ea.FundingAward() ...
python
def build_funding(award_groups): """ Given a funding data, format it """ if not award_groups: return [] funding_awards = [] for award_groups_item in award_groups: for award_group_id, award_group in iteritems(award_groups_item): award = ea.FundingAward() ...
[ "def", "build_funding", "(", "award_groups", ")", ":", "if", "not", "award_groups", ":", "return", "[", "]", "funding_awards", "=", "[", "]", "for", "award_groups_item", "in", "award_groups", ":", "for", "award_group_id", ",", "award_group", "in", "iteritems", ...
Given a funding data, format it
[ "Given", "a", "funding", "data", "format", "it" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L78-L102
elifesciences/elife-article
elifearticle/parse.py
build_datasets
def build_datasets(datasets_json): """ Given datasets in JSON format, build and return a list of dataset objects """ if not datasets_json: return [] datasets = [] dataset_type_map = OrderedDict([ ('generated', 'datasets'), ('used', 'prev_published_datasets') ]) d...
python
def build_datasets(datasets_json): """ Given datasets in JSON format, build and return a list of dataset objects """ if not datasets_json: return [] datasets = [] dataset_type_map = OrderedDict([ ('generated', 'datasets'), ('used', 'prev_published_datasets') ]) d...
[ "def", "build_datasets", "(", "datasets_json", ")", ":", "if", "not", "datasets_json", ":", "return", "[", "]", "datasets", "=", "[", "]", "dataset_type_map", "=", "OrderedDict", "(", "[", "(", "'generated'", ",", "'datasets'", ")", ",", "(", "'used'", ","...
Given datasets in JSON format, build and return a list of dataset objects
[ "Given", "datasets", "in", "JSON", "format", "build", "and", "return", "a", "list", "of", "dataset", "objects" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L105-L147
elifesciences/elife-article
elifearticle/parse.py
build_data_availability
def build_data_availability(datasets_json): """ Given datasets in JSON format, get the data availability from it if present """ data_availability = None if 'availability' in datasets_json and datasets_json.get('availability'): # only expect one paragraph of text data_availability = d...
python
def build_data_availability(datasets_json): """ Given datasets in JSON format, get the data availability from it if present """ data_availability = None if 'availability' in datasets_json and datasets_json.get('availability'): # only expect one paragraph of text data_availability = d...
[ "def", "build_data_availability", "(", "datasets_json", ")", ":", "data_availability", "=", "None", "if", "'availability'", "in", "datasets_json", "and", "datasets_json", ".", "get", "(", "'availability'", ")", ":", "# only expect one paragraph of text", "data_availabilit...
Given datasets in JSON format, get the data availability from it if present
[ "Given", "datasets", "in", "JSON", "format", "get", "the", "data", "availability", "from", "it", "if", "present" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L150-L158
elifesciences/elife-article
elifearticle/parse.py
build_ref_list
def build_ref_list(refs): """ Given parsed references build a list of ref objects """ ref_list = [] for reference in refs: ref = ea.Citation() # Publcation Type utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type')) # id utils.set_...
python
def build_ref_list(refs): """ Given parsed references build a list of ref objects """ ref_list = [] for reference in refs: ref = ea.Citation() # Publcation Type utils.set_attr_if_value(ref, 'publication_type', reference.get('publication-type')) # id utils.set_...
[ "def", "build_ref_list", "(", "refs", ")", ":", "ref_list", "=", "[", "]", "for", "reference", "in", "refs", ":", "ref", "=", "ea", ".", "Citation", "(", ")", "# Publcation Type", "utils", ".", "set_attr_if_value", "(", "ref", ",", "'publication_type'", ",...
Given parsed references build a list of ref objects
[ "Given", "parsed", "references", "build", "a", "list", "of", "ref", "objects" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L161-L252
elifesciences/elife-article
elifearticle/parse.py
component_title
def component_title(component): """ Label, title and caption Title is the label text plus the title text Title may contain italic tag, etc. """ title = u'' label_text = u'' title_text = u'' if component.get('label'): label_text = component.get('label') if component.get...
python
def component_title(component): """ Label, title and caption Title is the label text plus the title text Title may contain italic tag, etc. """ title = u'' label_text = u'' title_text = u'' if component.get('label'): label_text = component.get('label') if component.get...
[ "def", "component_title", "(", "component", ")", ":", "title", "=", "u''", "label_text", "=", "u''", "title_text", "=", "u''", "if", "component", ".", "get", "(", "'label'", ")", ":", "label_text", "=", "component", ".", "get", "(", "'label'", ")", "if",...
Label, title and caption Title is the label text plus the title text Title may contain italic tag, etc.
[ "Label", "title", "and", "caption", "Title", "is", "the", "label", "text", "plus", "the", "title", "text", "Title", "may", "contain", "italic", "tag", "etc", "." ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L255-L280
elifesciences/elife-article
elifearticle/parse.py
build_components
def build_components(components): """ Given parsed components build a list of component objects """ component_list = [] for comp in components: component = ea.Component() # id component.id = comp.get('id') # type component.type = comp.get('type') #...
python
def build_components(components): """ Given parsed components build a list of component objects """ component_list = [] for comp in components: component = ea.Component() # id component.id = comp.get('id') # type component.type = comp.get('type') #...
[ "def", "build_components", "(", "components", ")", ":", "component_list", "=", "[", "]", "for", "comp", "in", "components", ":", "component", "=", "ea", ".", "Component", "(", ")", "# id", "component", ".", "id", "=", "comp", ".", "get", "(", "'id'", "...
Given parsed components build a list of component objects
[ "Given", "parsed", "components", "build", "a", "list", "of", "component", "objects" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L283-L332
elifesciences/elife-article
elifearticle/parse.py
build_related_articles
def build_related_articles(related_articles): """ Given parsed data build a list of related article objects """ article_list = [] for related_article in related_articles: article = ea.RelatedArticle() if related_article.get('xlink_href'): article.xlink_href = related_art...
python
def build_related_articles(related_articles): """ Given parsed data build a list of related article objects """ article_list = [] for related_article in related_articles: article = ea.RelatedArticle() if related_article.get('xlink_href'): article.xlink_href = related_art...
[ "def", "build_related_articles", "(", "related_articles", ")", ":", "article_list", "=", "[", "]", "for", "related_article", "in", "related_articles", ":", "article", "=", "ea", ".", "RelatedArticle", "(", ")", "if", "related_article", ".", "get", "(", "'xlink_h...
Given parsed data build a list of related article objects
[ "Given", "parsed", "data", "build", "a", "list", "of", "related", "article", "objects" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L335-L353
elifesciences/elife-article
elifearticle/parse.py
build_pub_dates
def build_pub_dates(article, pub_dates): "convert pub_dates into ArticleDate objects and add them to article" for pub_date in pub_dates: # always want a date type, take it from pub-type if must if pub_date.get('date-type'): date_instance = ea.ArticleDate(pub_date.get('date-type'), ...
python
def build_pub_dates(article, pub_dates): "convert pub_dates into ArticleDate objects and add them to article" for pub_date in pub_dates: # always want a date type, take it from pub-type if must if pub_date.get('date-type'): date_instance = ea.ArticleDate(pub_date.get('date-type'), ...
[ "def", "build_pub_dates", "(", "article", ",", "pub_dates", ")", ":", "for", "pub_date", "in", "pub_dates", ":", "# always want a date type, take it from pub-type if must", "if", "pub_date", ".", "get", "(", "'date-type'", ")", ":", "date_instance", "=", "ea", ".", ...
convert pub_dates into ArticleDate objects and add them to article
[ "convert", "pub_dates", "into", "ArticleDate", "objects", "and", "add", "them", "to", "article" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L356-L373
elifesciences/elife-article
elifearticle/parse.py
build_self_uri_list
def build_self_uri_list(self_uri_list): "parse the self-uri tags, build Uri objects" uri_list = [] for self_uri in self_uri_list: uri = ea.Uri() utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href')) utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-t...
python
def build_self_uri_list(self_uri_list): "parse the self-uri tags, build Uri objects" uri_list = [] for self_uri in self_uri_list: uri = ea.Uri() utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href')) utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-t...
[ "def", "build_self_uri_list", "(", "self_uri_list", ")", ":", "uri_list", "=", "[", "]", "for", "self_uri", "in", "self_uri_list", ":", "uri", "=", "ea", ".", "Uri", "(", ")", "utils", ".", "set_attr_if_value", "(", "uri", ",", "'xlink_href'", ",", "self_u...
parse the self-uri tags, build Uri objects
[ "parse", "the", "self", "-", "uri", "tags", "build", "Uri", "objects" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L376-L384
elifesciences/elife-article
elifearticle/parse.py
clean_abstract
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']): """ Remove unwanted tags from abstract string, parsing it as HTML, then only keep the body paragraph contents """ if remove_tags: for tag_name in remove_tags: abstract = utils.remove_tag(ta...
python
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']): """ Remove unwanted tags from abstract string, parsing it as HTML, then only keep the body paragraph contents """ if remove_tags: for tag_name in remove_tags: abstract = utils.remove_tag(ta...
[ "def", "clean_abstract", "(", "abstract", ",", "remove_tags", "=", "[", "'xref'", ",", "'ext-link'", ",", "'inline-formula'", ",", "'mml:*'", "]", ")", ":", "if", "remove_tags", ":", "for", "tag_name", "in", "remove_tags", ":", "abstract", "=", "utils", ".",...
Remove unwanted tags from abstract string, parsing it as HTML, then only keep the body paragraph contents
[ "Remove", "unwanted", "tags", "from", "abstract", "string", "parsing", "it", "as", "HTML", "then", "only", "keep", "the", "body", "paragraph", "contents" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L387-L395
elifesciences/elife-article
elifearticle/parse.py
build_article_from_xml
def build_article_from_xml(article_xml_filename, detail="brief", build_parts=None, remove_tags=None): """ Parse JATS XML with elifetools parser, and populate an eLifePOA article object Basic data crossref needs: article_id, doi, title, contributors with names set detail="b...
python
def build_article_from_xml(article_xml_filename, detail="brief", build_parts=None, remove_tags=None): """ Parse JATS XML with elifetools parser, and populate an eLifePOA article object Basic data crossref needs: article_id, doi, title, contributors with names set detail="b...
[ "def", "build_article_from_xml", "(", "article_xml_filename", ",", "detail", "=", "\"brief\"", ",", "build_parts", "=", "None", ",", "remove_tags", "=", "None", ")", ":", "build_part", "=", "lambda", "part", ":", "build_part_check", "(", "part", ",", "build_part...
Parse JATS XML with elifetools parser, and populate an eLifePOA article object Basic data crossref needs: article_id, doi, title, contributors with names set detail="brief" is normally enough, detail="full" will populate all the contributor affiliations that are linked by xref tags
[ "Parse", "JATS", "XML", "with", "elifetools", "parser", "and", "populate", "an", "eLifePOA", "article", "object", "Basic", "data", "crossref", "needs", ":", "article_id", "doi", "title", "contributors", "with", "names", "set", "detail", "=", "brief", "is", "no...
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L408-L568
elifesciences/elife-article
elifearticle/parse.py
build_articles_from_article_xmls
def build_articles_from_article_xmls(article_xmls, detail="full", build_parts=None, remove_tags=None): """ Given a list of article XML filenames, convert to article objects """ poa_articles = [] for article_xml in article_xmls: print("working on ", arti...
python
def build_articles_from_article_xmls(article_xmls, detail="full", build_parts=None, remove_tags=None): """ Given a list of article XML filenames, convert to article objects """ poa_articles = [] for article_xml in article_xmls: print("working on ", arti...
[ "def", "build_articles_from_article_xmls", "(", "article_xmls", ",", "detail", "=", "\"full\"", ",", "build_parts", "=", "None", ",", "remove_tags", "=", "None", ")", ":", "poa_articles", "=", "[", "]", "for", "article_xml", "in", "article_xmls", ":", "print", ...
Given a list of article XML filenames, convert to article objects
[ "Given", "a", "list", "of", "article", "XML", "filenames", "convert", "to", "article", "objects" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L571-L586
CivicSpleen/ckcache
ckcache/__init__.py
accounts
def accounts(): """Load the accounts YAML file and return a dict """ import yaml for path in account_files: try: c_dir = os.path.dirname(path) if not os.path.exists(c_dir): os.makedirs(c_dir) with open(path, 'rb') as f: return y...
python
def accounts(): """Load the accounts YAML file and return a dict """ import yaml for path in account_files: try: c_dir = os.path.dirname(path) if not os.path.exists(c_dir): os.makedirs(c_dir) with open(path, 'rb') as f: return y...
[ "def", "accounts", "(", ")", ":", "import", "yaml", "for", "path", "in", "account_files", ":", "try", ":", "c_dir", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "c_dir", ")", ":", "...
Load the accounts YAML file and return a dict
[ "Load", "the", "accounts", "YAML", "file", "and", "return", "a", "dict" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L57-L75
CivicSpleen/ckcache
ckcache/__init__.py
new_cache
def new_cache(config, root_dir='no_root_dir'): """Return a new :class:`FsCache` built on the configured cache directory """ if isinstance(config, basestring): config = parse_cache_string(config, root_dir) if 'size' in config: from filesystem import FsLimitedCache fsclass = FsLi...
python
def new_cache(config, root_dir='no_root_dir'): """Return a new :class:`FsCache` built on the configured cache directory """ if isinstance(config, basestring): config = parse_cache_string(config, root_dir) if 'size' in config: from filesystem import FsLimitedCache fsclass = FsLi...
[ "def", "new_cache", "(", "config", ",", "root_dir", "=", "'no_root_dir'", ")", ":", "if", "isinstance", "(", "config", ",", "basestring", ")", ":", "config", "=", "parse_cache_string", "(", "config", ",", "root_dir", ")", "if", "'size'", "in", "config", ":...
Return a new :class:`FsCache` built on the configured cache directory
[ "Return", "a", "new", ":", "class", ":", "FsCache", "built", "on", "the", "configured", "cache", "directory" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L78-L140
CivicSpleen/ckcache
ckcache/__init__.py
get_logger
def get_logger( name, file_name=None, stream=None, template=None, propagate=False): """Get a logger by name if file_name is specified, and the dirname() of the file_name exists, it will write to that file. If the dirname dies not exist, it will silently ignre it. """ logger = logging.getLogger...
python
def get_logger( name, file_name=None, stream=None, template=None, propagate=False): """Get a logger by name if file_name is specified, and the dirname() of the file_name exists, it will write to that file. If the dirname dies not exist, it will silently ignre it. """ logger = logging.getLogger...
[ "def", "get_logger", "(", "name", ",", "file_name", "=", "None", ",", "stream", "=", "None", ",", "template", "=", "None", ",", "propagate", "=", "False", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "if", "propagate", "is", ...
Get a logger by name if file_name is specified, and the dirname() of the file_name exists, it will write to that file. If the dirname dies not exist, it will silently ignre it.
[ "Get", "a", "logger", "by", "name" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L758-L800
CivicSpleen/ckcache
ckcache/__init__.py
md5_for_file
def md5_for_file(f, block_size=2 ** 20): """Generate an MD5 has for a possibly large file by breaking it into chunks""" import hashlib md5 = hashlib.md5() try: # Guess that f is a FLO. f.seek(0) while True: data = f.read(block_size) if not data: ...
python
def md5_for_file(f, block_size=2 ** 20): """Generate an MD5 has for a possibly large file by breaking it into chunks""" import hashlib md5 = hashlib.md5() try: # Guess that f is a FLO. f.seek(0) while True: data = f.read(block_size) if not data: ...
[ "def", "md5_for_file", "(", "f", ",", "block_size", "=", "2", "**", "20", ")", ":", "import", "hashlib", "md5", "=", "hashlib", ".", "md5", "(", ")", "try", ":", "# Guess that f is a FLO.", "f", ".", "seek", "(", "0", ")", "while", "True", ":", "data...
Generate an MD5 has for a possibly large file by breaking it into chunks
[ "Generate", "an", "MD5", "has", "for", "a", "possibly", "large", "file", "by", "breaking", "it", "into", "chunks" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L803-L824
CivicSpleen/ckcache
ckcache/__init__.py
Cache.subcache
def subcache(self, path): """Clone this case, and extend the prefix""" cache = self.clone() cache.prefix = os.path.join(cache.prefix if cache.prefix else '', path) return cache
python
def subcache(self, path): """Clone this case, and extend the prefix""" cache = self.clone() cache.prefix = os.path.join(cache.prefix if cache.prefix else '', path) return cache
[ "def", "subcache", "(", "self", ",", "path", ")", ":", "cache", "=", "self", ".", "clone", "(", ")", "cache", ".", "prefix", "=", "os", ".", "path", ".", "join", "(", "cache", ".", "prefix", "if", "cache", ".", "prefix", "else", "''", ",", "path"...
Clone this case, and extend the prefix
[ "Clone", "this", "case", "and", "extend", "the", "prefix" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L214-L220
CivicSpleen/ckcache
ckcache/__init__.py
Cache.store_list
def store_list(self, cb=None): """List the cache and store it as metadata. This allows for getting the list from HTTP caches and other types where it is not possible to traverse the tree""" from StringIO import StringIO import json d = {} for k, v in self.list().items(...
python
def store_list(self, cb=None): """List the cache and store it as metadata. This allows for getting the list from HTTP caches and other types where it is not possible to traverse the tree""" from StringIO import StringIO import json d = {} for k, v in self.list().items(...
[ "def", "store_list", "(", "self", ",", "cb", "=", "None", ")", ":", "from", "StringIO", "import", "StringIO", "import", "json", "d", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "list", "(", ")", ".", "items", "(", ")", ":", "if", "'...
List the cache and store it as metadata. This allows for getting the list from HTTP caches and other types where it is not possible to traverse the tree
[ "List", "the", "cache", "and", "store", "it", "as", "metadata", ".", "This", "allows", "for", "getting", "the", "list", "from", "HTTP", "caches", "and", "other", "types", "where", "it", "is", "not", "possible", "to", "traverse", "the", "tree" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L327-L348
CivicSpleen/ckcache
ckcache/__init__.py
Cache.attach
def attach(self, upstream): """Attach an upstream to the last upstream. Can be removed with detach""" if upstream == self.last_upstream(): raise Exception("Can't attach a cache to itself") self._prior_upstreams.append(self.last_upstream()) self.last_upstream().upstream = u...
python
def attach(self, upstream): """Attach an upstream to the last upstream. Can be removed with detach""" if upstream == self.last_upstream(): raise Exception("Can't attach a cache to itself") self._prior_upstreams.append(self.last_upstream()) self.last_upstream().upstream = u...
[ "def", "attach", "(", "self", ",", "upstream", ")", ":", "if", "upstream", "==", "self", ".", "last_upstream", "(", ")", ":", "raise", "Exception", "(", "\"Can't attach a cache to itself\"", ")", "self", ".", "_prior_upstreams", ".", "append", "(", "self", "...
Attach an upstream to the last upstream. Can be removed with detach
[ "Attach", "an", "upstream", "to", "the", "last", "upstream", ".", "Can", "be", "removed", "with", "detach" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L350-L358
CivicSpleen/ckcache
ckcache/__init__.py
Cache.get_upstream
def get_upstream(self, type_): '''Return self, or an upstream, that has the given class type. This is typically used to find upstream s that impoement the RemoteInterface ''' if isinstance(self, type_): return self elif self.upstream and isinstance(self.upstream, typ...
python
def get_upstream(self, type_): '''Return self, or an upstream, that has the given class type. This is typically used to find upstream s that impoement the RemoteInterface ''' if isinstance(self, type_): return self elif self.upstream and isinstance(self.upstream, typ...
[ "def", "get_upstream", "(", "self", ",", "type_", ")", ":", "if", "isinstance", "(", "self", ",", "type_", ")", ":", "return", "self", "elif", "self", ".", "upstream", "and", "isinstance", "(", "self", ".", "upstream", ",", "type_", ")", ":", "return",...
Return self, or an upstream, that has the given class type. This is typically used to find upstream s that impoement the RemoteInterface
[ "Return", "self", "or", "an", "upstream", "that", "has", "the", "given", "class", "type", ".", "This", "is", "typically", "used", "to", "find", "upstream", "s", "that", "impoement", "the", "RemoteInterface" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/__init__.py#L373-L385
MacHu-GWU/angora-project
angora/crawler/simplecrawler.py
SmartDecoder.decode
def decode(self, a_bytes, encoding): """A 'try as much as we can' strategy decoding method. 'try as much as we can' feature: Some time most of byte are encoded correctly. So chardet is able to detect the encoding. But, sometime some bytes in the middle are not encoded correctly...
python
def decode(self, a_bytes, encoding): """A 'try as much as we can' strategy decoding method. 'try as much as we can' feature: Some time most of byte are encoded correctly. So chardet is able to detect the encoding. But, sometime some bytes in the middle are not encoded correctly...
[ "def", "decode", "(", "self", ",", "a_bytes", ",", "encoding", ")", ":", "try", ":", "return", "(", "a_bytes", ".", "decode", "(", "encoding", ")", ",", "encoding", ")", "except", "Exception", "as", "e", ":", "ind", "=", "self", ".", "catch_position_in...
A 'try as much as we can' strategy decoding method. 'try as much as we can' feature: Some time most of byte are encoded correctly. So chardet is able to detect the encoding. But, sometime some bytes in the middle are not encoded correctly. So it is still unable to apply bytes.d...
[ "A", "try", "as", "much", "as", "we", "can", "strategy", "decoding", "method", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/crawler/simplecrawler.py#L62-L91
MacHu-GWU/angora-project
angora/crawler/simplecrawler.py
SmartDecoder.autodecode
def autodecode(self, a_bytes): """Automatically detect encoding, and decode bytes. """ try: # 如果装了chardet analysis = chardet.detect(a_bytes) if analysis["confidence"] >= 0.75: # 如果可信 return (self.decode(a_bytes, analysis["encoding"])[0], ...
python
def autodecode(self, a_bytes): """Automatically detect encoding, and decode bytes. """ try: # 如果装了chardet analysis = chardet.detect(a_bytes) if analysis["confidence"] >= 0.75: # 如果可信 return (self.decode(a_bytes, analysis["encoding"])[0], ...
[ "def", "autodecode", "(", "self", ",", "a_bytes", ")", ":", "try", ":", "# 如果装了chardet", "analysis", "=", "chardet", ".", "detect", "(", "a_bytes", ")", "if", "analysis", "[", "\"confidence\"", "]", ">=", "0.75", ":", "# 如果可信", "return", "(", "self", "."...
Automatically detect encoding, and decode bytes.
[ "Automatically", "detect", "encoding", "and", "decode", "bytes", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/crawler/simplecrawler.py#L93-L109