code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def set_config_local(self, path):
"""Set the local configration via file path.
This will override project defaults in the final configuration.
If no local configuration is found on the argument path, a warning will be shown, and only default config is used.
Arguments:
path {str} --... | Set the local configration via file path.
This will override project defaults in the final configuration.
If no local configuration is found on the argument path, a warning will be shown, and only default config is used.
Arguments:
path {str} -- Local config file location
| set_config_local | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def __read_yaml_file(self, path):
"""Open the yaml file and load it to the variable.
Return created list"""
with open(path) as f:
yaml_fields = yaml.load_all(f.read(), Loader=yaml.FullLoader)
buff_results = [x for x in yaml_fields]
if len(buff_results) > 1:
... | Open the yaml file and load it to the variable.
Return created list | __read_yaml_file | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def read_rule_file(path):
"""Open the file and load it to the variable. Return text"""
with open(path) as f:
rule_text = f.read()
return rule_text | Open the file and load it to the variable. Return text | read_rule_file | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def read_yaml_file(path):
"""Open the yaml file and load it to the variable.
Return created list"""
if path == 'config.yml':
wrn = "Use 'load_config' or 'ATCConfig' instead for config"
# Warning will not show,
# unless captured by logging facility or python c... | Open the yaml file and load it to the variable.
Return created list | read_yaml_file | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def confluence_get_page_id(apipath, auth, space, title):
"""Get confluence page ID based on title and space"""
headers = {
"Accept": "application/json",
"Content-Type": "application/json"
}
url = apipath + "content"
space_page_url = url + '?spaceKey=' + ... | Get confluence page ID based on title and space | confluence_get_page_id | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def sigma_lgsrc_fields_to_names(logsource_dict):
"""Get sigma logsource dict and rename key/values into our model,
so we could use it for Data Needed calculation"""
if logsource_dict:
sigma_keys = [*sigma_mapping]
proper_logsource_dict = {}
for ke... | Get sigma logsource dict and rename key/values into our model,
so we could use it for Data Needed calculation | sigma_lgsrc_fields_to_names | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def check_for_event_ids_presence(detection_rule_obj):
"""check if this is event id based detection rule"""
if detection_rule_obj.get('detection'):
for _field in detection_rule_obj['detection']:
if _field in ["condition", "timeframe"]:
continue
... | check if this is event id based detection rule | check_for_event_ids_presence | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def check_for_enrichment_presence(detection_rule_obj):
"""check if this Data for this Detection Rule required any enrichments"""
if detection_rule_obj.get('enrichment'):
return True
else:
return False | check if this Data for this Detection Rule required any enrichments | check_for_enrichment_presence | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def get_logsource_of_the_document(detection_rule_obj):
"""get logsource for specific document (addition)"""
logsource = {}
_temp_list = []
logsource_optional_fields = ['category', 'product', 'service']
if 'logsource' in detection_rule_obj:
for val in logsource_optio... | get logsource for specific document (addition) | get_logsource_of_the_document | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def calculate_dn_for_eventid_based_dr(
dn_list, logsource, event_ids, has_command_line):
"""Meaning of the arguments:
dn_list - list of Data Needed objects (all dataneeded!)
logsource - dictionary of logsource fields of Detection Rule PER document
event_ids - list of event id... | Meaning of the arguments:
dn_list - list of Data Needed objects (all dataneeded!)
logsource - dictionary of logsource fields of Detection Rule PER document
event_ids - list of event ids per selection
logsource = {
"product": "windows",
"service": "sysmon"
... | calculate_dn_for_eventid_based_dr | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def calculate_dn_for_non_eventid_based_dr(
dn_list, detection_fields, logsource):
"""Meaning of the arguments:
dn_list - list of Data Needed objects (all dataneeded!)
detection_fields - dictionary of fields from detection section of
Detection Rule
l... | Meaning of the arguments:
dn_list - list of Data Needed objects (all dataneeded!)
detection_fields - dictionary of fields from detection section of
Detection Rule
logsource - dictionary of logsource fields of Detection Rule
detection_fields = {
"Com... | calculate_dn_for_non_eventid_based_dr | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def write_file(path, content, options="w+"):
"""Simple method for writing content to some file"""
with open(path, options) as file:
file.write(content)
return True | Simple method for writing content to some file | write_file | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def get_rules(self):
""" Retruns list of detection rules for customer
"""
dr_list_per_customer = [rules_by_title.get(dr_title)[0]
for dr_title in self.detection_rules]
return dr_list_per_customer | Retruns list of detection rules for customer
| get_rules | python | atc-project/atomic-threat-coverage | scripts/customer.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/customer.py | Apache-2.0 |
def get_usecases(self):
""" Retruns list of use cases for customer
"""
uc_list_per_customer = [usecases_by_title.get(uc_title)[0]
for uc_title in self.use_cases]
return uc_list_per_customer | Retruns list of use cases for customer
| get_usecases | python | atc-project/atomic-threat-coverage | scripts/customer.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/customer.py | Apache-2.0 |
def render_template(self, template_type):
"""Render template with data in it
template_type:
- "markdown"
- "confluence"
"""
if template_type not in ["markdown", "confluence"]:
raise Exception(
"Bad template_type. Available values: " +
... | Render template with data in it
template_type:
- "markdown"
- "confluence"
| render_template | python | atc-project/atomic-threat-coverage | scripts/customer.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/customer.py | Apache-2.0 |
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory')):
"""Write content (md template filled with data) to a file"""
base = os.path.basename(self.yaml_file)
title = os.path.splitext(base)[0]
file_path = atc_dir + self.parent_title + "/" + \
title +... | Write content (md template filled with data) to a file | save_markdown_file | python | atc-project/atomic-threat-coverage | scripts/customer.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/customer.py | Apache-2.0 |
def render_template(self, template_type):
"""Render template with data in it
template_type:
- "markdown"
- "confluence"
"""
if template_type not in ["markdown", "confluence"]:
raise Exception(
"Bad template_type. Available values: " +
... | Render template with data in it
template_type:
- "markdown"
- "confluence"
| render_template | python | atc-project/atomic-threat-coverage | scripts/detectionrule.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/detectionrule.py | Apache-2.0 |
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory') + '/'):
"""Write content (md template filled with data) to a file"""
base = os.path.basename(self.yaml_file)
title = os.path.splitext(base)[0]
file_path = atc_dir + self.parent_title + "/" + \
ti... | Write content (md template filled with data) to a file | save_markdown_file | python | atc-project/atomic-threat-coverage | scripts/detectionrule.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/detectionrule.py | Apache-2.0 |
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory')):
"""Write content (md template filled with data) to a file"""
base = os.path.basename(self.yaml_file)
title = os.path.splitext(base)[0]
file_path = atc_dir + self.parent_title + "/" + \
title +... | Write content (md template filled with data) to a file | save_markdown_file | python | atc-project/atomic-threat-coverage | scripts/hardeningpolicy.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/hardeningpolicy.py | Apache-2.0 |
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory')):
"""Write content (md template filled with data) to a file"""
base = os.path.basename(self.yaml_file)
title = os.path.splitext(base)[0]
file_path = atc_dir + self.parent_title + "/" + \
title +... | Write content (md template filled with data) to a file | save_markdown_file | python | atc-project/atomic-threat-coverage | scripts/mitigationpolicy.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/mitigationpolicy.py | Apache-2.0 |
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory')):
"""Write content (md template filled with data) to a file"""
base = os.path.basename(self.yaml_file)
title = os.path.splitext(base)[0]
file_path = atc_dir + self.parent_title + "/" + \
title +... | Write content (md template filled with data) to a file | save_markdown_file | python | atc-project/atomic-threat-coverage | scripts/mitigationsystem.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/mitigationsystem.py | Apache-2.0 |
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory')):
"""Write content (md template filled with data) to a file"""
base = os.path.basename(self.yaml_file)
title = os.path.splitext(base)[0]
file_path = atc_dir + self.parent_title + "/" + \
title +... | Write content (md template filled with data) to a file | save_markdown_file | python | atc-project/atomic-threat-coverage | scripts/triggers.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/triggers.py | Apache-2.0 |
def get_rules(self):
""" Retruns list of detection rules for usecase
"""
dr_list_per_usecase = [rules_by_title.get(dr_title)[0]
for dr_title in self.detection_rules]
return dr_list_per_usecase | Retruns list of detection rules for usecase
| get_rules | python | atc-project/atomic-threat-coverage | scripts/usecases.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/usecases.py | Apache-2.0 |
def render_template(self, template_type):
"""Render template with data in it
template_type:
- "markdown"
- "confluence"
"""
if template_type not in ["markdown", "confluence"]:
raise Exception(
"Bad template_type. Available values: " +
... | Render template with data in it
template_type:
- "markdown"
- "confluence"
| render_template | python | atc-project/atomic-threat-coverage | scripts/usecases.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/usecases.py | Apache-2.0 |
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory')):
"""Write content (md template filled with data) to a file"""
base = os.path.basename(self.yaml_file)
title = os.path.splitext(base)[0]
file_path = atc_dir + self.parent_title + "/" + \
title +... | Write content (md template filled with data) to a file | save_markdown_file | python | atc-project/atomic-threat-coverage | scripts/usecases.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/usecases.py | Apache-2.0 |
def __init__(self, id, field, enabled=None):
"""field - field name which should be averaged"""
super().__init__(
id=id, enabled=enabled, type="avg", schema="metric", params={
"field": field
}
) | field - field name which should be averaged | __init__ | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/aggs.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/aggs.py | Apache-2.0 |
def __init__(self, id, field, aggregate_with, size, sort_order, sort_field,
enabled=None):
"""aggregate_with - can be average, max, min or sum
size - integer
sort_order - can be asc or dsc
"""
super().__init__(
id=id, enabled=enabled, params={
"aggregate": ag... | aggregate_with - can be average, max, min or sum
size - integer
sort_order - can be asc or dsc
| __init__ | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/aggs.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/aggs.py | Apache-2.0 |
def validate(self):
# TODO: Write custom validate (validate every required field)
"""
sort_order - either `asc` or `desc`
size - int positive number
aggregate_with - ["average", "concat", "min", "max", "sum"]
"""
return super().validate() |
sort_order - either `asc` or `desc`
size - int positive number
aggregate_with - ["average", "concat", "min", "max", "sum"]
| validate | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/aggs.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/aggs.py | Apache-2.0 |
def search_id_of_title_by_type(cls, search_type, search_title):
"""Returns an ID (string) of an object searched using object title
search_type - string in ["index-pattern", "search"]
search_title - string
"""
search_type = search_type.lower()
if search_type not in ["index-pattern", "search"]:
... | Returns an ID (string) of an object searched using object title
search_type - string in ["index-pattern", "search"]
search_title - string
| search_id_of_title_by_type | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/base.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/base.py | Apache-2.0 |
def get_all(self):
"""Get all saved objects and put them into visualization/dashboards"""
r = self.es.search(
index='.kibana*', doc_type='',
body={'query': {'match_all': {}}},
size=self.search_limit_size,
)
for obj in r['hits']['hits']:
i... | Get all saved objects and put them into visualization/dashboards | get_all | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/kibana_api.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/kibana_api.py | Apache-2.0 |
def json_export_gui(self, return_dict=False, uuid_=None):
"""visState has to be a string with escaped doublequotes"""
if self.validate():
# self.updated_at = datetime.datetime.today().isoformat() + "Z"
# TODO: Find proper way to do below line :))
tmp_dictionary = lite... | visState has to be a string with escaped doublequotes | json_export_gui | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/visualisation.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/visualisation.py | Apache-2.0 |
def json_export_api(self, return_dict=False, uuid_=None):
"""visState has to be a string with escaped doublequotes"""
if self.validate():
# self.updated_at = datetime.datetime.today().isoformat() + "Z"
# TODO: Find proper way to do below line :))
tmp_dictionary = lite... | visState has to be a string with escaped doublequotes | json_export_api | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/visualisation.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/visualisation.py | Apache-2.0 |
def set_saved_search(self, saved_search_name=None, saved_search_id=None):
"""Provide ID if you know it and don't want to engage kibana"""
if not saved_search_name and not saved_search_id:
raise Exception(
"What's the point of running this method without arguments?"
... | Provide ID if you know it and don't want to engage kibana | set_saved_search | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/visualisation.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/visualisation.py | Apache-2.0 |
def validate(opts, model, loader, device, metrics, ret_samples_ids=None):
"""Do validation and return specified samples"""
metrics.reset()
ret_samples = []
if opts.save_val_results:
if not os.path.exists('results'):
os.mkdir('results')
denorm = utils.Denormalize(mean=[0.485, ... | Do validation and return specified samples | validate | python | VainF/DeepLabV3Plus-Pytorch | main.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/main.py | MIT |
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is a tuple of all target types if target_type is a list with more
than one item. Otherwise target is a json object if target_type="polygon", else the image ... |
Args:
index (int): Index
Returns:
tuple: (image, target) where target is a tuple of all target types if target_type is a list with more
than one item. Otherwise target is a json object if target_type="polygon", else the image segmentation.
| __getitem__ | python | VainF/DeepLabV3Plus-Pytorch | datasets/cityscapes.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/cityscapes.py | MIT |
def download_url(url, root, filename=None, md5=None):
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str): Name to save the file under. If None, use the basename of the URL
... | Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str): Name to save the file under. If None, use the basename of the URL
md5 (str): MD5 checksum of the download. If None, do not che... | download_url | python | VainF/DeepLabV3Plus-Pytorch | datasets/utils.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/utils.py | MIT |
def list_dir(root, prefix=False):
"""List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
"""
root ... | List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
| list_dir | python | VainF/DeepLabV3Plus-Pytorch | datasets/utils.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/utils.py | MIT |
def list_files(root, suffix, prefix=False):
"""List all files ending with a suffix at a given root
Args:
root (str): Path to directory whose folders need to be listed
suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
It uses the Python "str.endswit... | List all files ending with a suffix at a given root
Args:
root (str): Path to directory whose folders need to be listed
suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
It uses the Python "str.endswith" method and is passed directly
prefix (bo... | list_files | python | VainF/DeepLabV3Plus-Pytorch | datasets/utils.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/utils.py | MIT |
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is the image segmentation.
"""
img = Image.open(self.images[index]).convert('RGB')
target = Image.open(self.masks[index])
if self.transf... |
Args:
index (int): Index
Returns:
tuple: (image, target) where target is the image segmentation.
| __getitem__ | python | VainF/DeepLabV3Plus-Pytorch | datasets/voc.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/voc.py | MIT |
def get_results(self):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
"""
hist = self.confusion_matrix
acc = np.diag(hist).sum() / hist.sum()
acc_cls = np.diag(hist) / hist.sum(ax... | Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
| get_results | python | VainF/DeepLabV3Plus-Pytorch | metrics/stream_metrics.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/metrics/stream_metrics.py | MIT |
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:... |
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
... | _make_divisible | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/mobilenetv2.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/mobilenetv2.py | MIT |
def __init__(self, num_classes=1000, output_stride=8, width_mult=1.0, inverted_residual_setting=None, round_nearest=8):
"""
MobileNet V2 main class
Args:
num_classes (int): Number of classes
width_mult (float): Width multiplier - adjusts number of channels in each layer ... |
MobileNet V2 main class
Args:
num_classes (int): Number of classes
width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount
inverted_residual_setting: Network structure
round_nearest (int): Round the number of channe... | __init__ | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/mobilenetv2.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/mobilenetv2.py | MIT |
def mobilenet_v2(pretrained=False, progress=True, **kwargs):
"""
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress ... |
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
... | mobilenet_v2 | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/mobilenetv2.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/mobilenetv2.py | MIT |
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): ... | ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext50_32x4d | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool)... | ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext101_32x8d | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in... | Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 ha... | wide_resnet50_2 | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels ... | Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 h... | wide_resnet101_2 | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
"""
if random.random() < self.p:
return F.hflip(img), F.hflip(lbl)
return img, lbl |
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be scaled.
lbl (PIL Image): Label to be scaled.
Returns:
PIL Image: Rescaled image.
PIL Image: Rescaled label.
"""
assert img.size == lbl.size
scale = random.... |
Args:
img (PIL Image): Image to be scaled.
lbl (PIL Image): Label to be scaled.
Returns:
PIL Image: Rescaled image.
PIL Image: Rescaled label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be scaled.
lbl (PIL Image): Label to be scaled.
Returns:
PIL Image: Rescaled image.
PIL Image: Rescaled label.
"""
assert img.size == lbl.size
target_size = (... |
Args:
img (PIL Image): Image to be scaled.
lbl (PIL Image): Label to be scaled.
Returns:
PIL Image: Rescaled image.
PIL Image: Rescaled label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
img (PIL Image): Image to be rotated.
lbl (PIL Image): Label to be rotated.
Returns:
PIL Image: Rotated image.
PIL Image: Rotated label.
"""
angle = self.get_params(self.degrees)
return F.rotate(i... |
img (PIL Image): Image to be rotated.
lbl (PIL Image): Label to be rotated.
Returns:
PIL Image: Rotated image.
PIL Image: Rotated label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
"""
if random.random() < self.p:
return F.hflip(img), F.hflip(lbl)
return img, lbl |
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be flipped.
lbl (PIL Image): Label to be flipped.
Returns:
PIL Image: Randomly flipped image.
PIL Image: Randomly flipped label.
"""
if random.random() < self.p:
... |
Args:
img (PIL Image): Image to be flipped.
lbl (PIL Image): Label to be flipped.
Returns:
PIL Image: Randomly flipped image.
PIL Image: Randomly flipped label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, pic, lbl):
"""
Note that labels will not be normalized to [0, 1].
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
lbl (PIL Image or numpy.ndarray): Label to be converted to tensor.
Returns:
Tensor: Converted... |
Note that labels will not be normalized to [0, 1].
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
lbl (PIL Image or numpy.ndarray): Label to be converted to tensor.
Returns:
Tensor: Converted image and label
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def get_params(img, output_size):
"""Get parameters for ``crop`` for a random crop.
Args:
img (PIL Image): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.... | Get parameters for ``crop`` for a random crop.
Args:
img (PIL Image): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
| get_params | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be cropped.
lbl (PIL Image): Label to be cropped.
Returns:
PIL Image: Cropped image.
PIL Image: Cropped label.
"""
assert img.size == lbl.size, 'size of img and lbl s... |
Args:
img (PIL Image): Image to be cropped.
lbl (PIL Image): Label to be cropped.
Returns:
PIL Image: Cropped image.
PIL Image: Cropped label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def get_params(brightness, contrast, saturation, hue):
"""Get a randomized transform to be applied on image.
Arguments are same as that of __init__.
Returns:
Transform which randomly adjusts brightness, contrast and
saturation in a random order.
"""
transf... | Get a randomized transform to be applied on image.
Arguments are same as that of __init__.
Returns:
Transform which randomly adjusts brightness, contrast and
saturation in a random order.
| get_params | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Input image.
Returns:
PIL Image: Color jittered image.
"""
transform = self.get_params(self.brightness, self.contrast,
self.saturation, self.hue)
return tr... |
Args:
img (PIL Image): Input image.
Returns:
PIL Image: Color jittered image.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def test_geosearch(self):
"""Test parsing a Wikipedia location request result."""
self.assertEqual(
wikipedia.geosearch(Decimal('40.67693'), Decimal('117.23193')),
mock_data['data']["great_wall_of_china.geo_seach"]
) | Test parsing a Wikipedia location request result. | test_geosearch | python | goldsmith/Wikipedia | tests/geosearch_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/geosearch_test.py | MIT |
def test_geosearch_with_radius(self):
"""Test parsing a Wikipedia location request result."""
self.assertEqual(wikipedia.geosearch(
Decimal('40.67693'), Decimal('117.23193'), radius=10000),
mock_data['data']["great_wall_of_china.geo_seach_with_radius"]
) | Test parsing a Wikipedia location request result. | test_geosearch_with_radius | python | goldsmith/Wikipedia | tests/geosearch_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/geosearch_test.py | MIT |
def test_geosearch_with_existing_title(self):
"""Test parsing a Wikipedia location request result."""
self.assertEqual(wikipedia.geosearch(
Decimal('40.67693'), Decimal('117.23193'), title='Great Wall of China'),
mock_data['data']["great_wall_of_china.geo_seach_with_existing_article_name"]
) | Test parsing a Wikipedia location request result. | test_geosearch_with_existing_title | python | goldsmith/Wikipedia | tests/geosearch_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/geosearch_test.py | MIT |
def test_missing(self):
"""Test that page raises a PageError for a nonexistant page."""
# Callicarpa?
purpleberry = lambda: wikipedia.page("purpleberry", auto_suggest=False)
self.assertRaises(wikipedia.PageError, purpleberry) | Test that page raises a PageError for a nonexistant page. | test_missing | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_true(self):
"""Test that a page successfully redirects a query."""
# no error should be raised if redirect is test_redirect_true
mp = wikipedia.page("Menlo Park, New Jersey")
self.assertEqual(mp.title, "Edison, New Jersey")
self.assertEqual(mp.url, "http://en.wikipedia.org/wiki/Ed... | Test that a page successfully redirects a query. | test_redirect_true | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_no_normalization(self):
"""Test that a page with redirects but no normalization query loads correctly"""
the_party = wikipedia.page("Communist Party", auto_suggest=False)
self.assertIsInstance(the_party, wikipedia.WikipediaPage)
self.assertEqual(the_party.title, "Communist party") | Test that a page with redirects but no normalization query loads correctly | test_redirect_no_normalization | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_with_normalization(self):
"""Test that a page redirect with a normalized query loads correctly"""
the_party = wikipedia.page("communist Party", auto_suggest=False)
self.assertIsInstance(the_party, wikipedia.WikipediaPage)
self.assertEqual(the_party.title, "Communist party") | Test that a page redirect with a normalized query loads correctly | test_redirect_with_normalization | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_normalization(self):
"""Test that a page redirect loads correctly with or without a query normalization"""
capital_party = wikipedia.page("Communist Party", auto_suggest=False)
lower_party = wikipedia.page("communist Party", auto_suggest=False)
self.assertIsInstance(capital_party, wik... | Test that a page redirect loads correctly with or without a query normalization | test_redirect_normalization | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_disambiguate(self):
"""Test that page raises an error when a disambiguation page is reached."""
try:
ram = wikipedia.page("Dodge Ram (disambiguation)", auto_suggest=False, redirect=False)
error_raised = False
except wikipedia.DisambiguationError as e:
error_raised = True
opt... | Test that page raises an error when a disambiguation page is reached. | test_disambiguate | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_suggestion(self):
"""Test getting a suggestion as well as search results."""
search, suggestion = wikipedia.search("hallelulejah", suggestion=True)
self.assertEqual(search, [])
self.assertEqual(suggestion, u'hallelujah') | Test getting a suggestion as well as search results. | test_suggestion | python | goldsmith/Wikipedia | tests/search_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/search_test.py | MIT |
def test_suggestion_none(self):
"""Test getting a suggestion when there is no suggestion."""
search, suggestion = wikipedia.search("qmxjsudek", suggestion=True)
self.assertEqual(search, [])
self.assertEqual(suggestion, None) | Test getting a suggestion when there is no suggestion. | test_suggestion_none | python | goldsmith/Wikipedia | tests/search_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/search_test.py | MIT |
def set_lang(prefix):
'''
Change the language of the API being requested.
Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.
After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared... |
Change the language of the API being requested.
Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.
After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared.
.. note:: Make sure yo... | set_lang | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def set_user_agent(user_agent_string):
'''
Set the User-Agent string to be used for all requests.
Arguments:
* user_agent_string - (string) a string specifying the User-Agent header
'''
global USER_AGENT
USER_AGENT = user_agent_string |
Set the User-Agent string to be used for all requests.
Arguments:
* user_agent_string - (string) a string specifying the User-Agent header
| set_user_agent | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def search(query, results=10, suggestion=False):
'''
Do a Wikipedia search for `query`.
Keyword arguments:
* results - the maxmimum number of results returned
* suggestion - if True, return results and suggestion (if any) in a tuple
'''
search_params = {
'list': 'search',
'srprop': '',
'srl... |
Do a Wikipedia search for `query`.
Keyword arguments:
* results - the maxmimum number of results returned
* suggestion - if True, return results and suggestion (if any) in a tuple
| search | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def geosearch(latitude, longitude, title=None, results=10, radius=1000):
'''
Do a wikipedia geo search for `latitude` and `longitude`
using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData
Arguments:
* latitude (float or decimal.Decimal)
* longitude (float or decimal.Decimal)
Keywo... |
Do a wikipedia geo search for `latitude` and `longitude`
using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData
Arguments:
* latitude (float or decimal.Decimal)
* longitude (float or decimal.Decimal)
Keyword arguments:
* title - The title of an article to search for
* results -... | geosearch | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def suggest(query):
'''
Get a Wikipedia search suggestion for `query`.
Returns a string or None if no suggestion was found.
'''
search_params = {
'list': 'search',
'srinfo': 'suggestion',
'srprop': '',
}
search_params['srsearch'] = query
raw_result = _wiki_request(search_params)
if raw_... |
Get a Wikipedia search suggestion for `query`.
Returns a string or None if no suggestion was found.
| suggest | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def random(pages=1):
'''
Get a list of random Wikipedia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
Keyword arguments:
* pages - the number of random pages returned (max of 10)
'''
#http://en.wikipedia.org/w/api.ph... |
Get a list of random Wikipedia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
Keyword arguments:
* pages - the number of random pages returned (max of 10)
| random | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True):
'''
Plain text summary of the page.
.. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default
Keyword arguments:
* sentences - if set, return the first `sentences` sentences (can be no greater than ... |
Plain text summary of the page.
.. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default
Keyword arguments:
* sentences - if set, return the first `sentences` sentences (can be no greater than 10).
* chars - if set, return only the first `chars` characters (actual text re... | summary | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False):
'''
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* a... |
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* auto_suggest - let Wikipedia find a valid page title for the query
* redirect - allow re... | page | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def __load(self, redirect=True, preload=False):
'''
Load basic information from Wikipedia.
Confirm that page exists and is not a disambiguation/redirect.
Does not need to be called manually, should be called automatically during __init__.
'''
query_params = {
'prop': 'info|pageprops',
... |
Load basic information from Wikipedia.
Confirm that page exists and is not a disambiguation/redirect.
Does not need to be called manually, should be called automatically during __init__.
| __load | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def __continued_query(self, query_params):
'''
Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries
'''
query_params.update(self.__title_query_param)
last_continue = {}
prop = query_params.get('prop', None)
while True:
params = query_params.copy()
params.update(... |
Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries
| __continued_query | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def html(self):
'''
Get full page HTML.
.. warning:: This can get pretty slow on long pages.
'''
if not getattr(self, '_html', False):
query_params = {
'prop': 'revisions',
'rvprop': 'content',
'rvlimit': 1,
'rvparse': '',
'titles': self.title
}
... |
Get full page HTML.
.. warning:: This can get pretty slow on long pages.
| html | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def content(self):
'''
Plain text content of the page, excluding images, tables, and other data.
'''
if not getattr(self, '_content', False):
query_params = {
'prop': 'extracts|revisions',
'explaintext': '',
'rvprop': 'ids'
}
if not getattr(self, 'title', None)... |
Plain text content of the page, excluding images, tables, and other data.
| content | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def revision_id(self):
'''
Revision ID of the page.
The revision ID is a number that uniquely identifies the current
version of the page. It can be used to create the permalink or for
other direct API calls. See `Help:Page history
<http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more
... |
Revision ID of the page.
The revision ID is a number that uniquely identifies the current
version of the page. It can be used to create the permalink or for
other direct API calls. See `Help:Page history
<http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more
information.
| revision_id | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def parent_id(self):
'''
Revision ID of the parent version of the current revision of this
page. See ``revision_id`` for more information.
'''
if not getattr(self, '_parentid', False):
# fetch the content (side effect is loading the revid)
self.content
return self._parent_id |
Revision ID of the parent version of the current revision of this
page. See ``revision_id`` for more information.
| parent_id | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def summary(self):
'''
Plain text summary of the page.
'''
if not getattr(self, '_summary', False):
query_params = {
'prop': 'extracts',
'explaintext': '',
'exintro': '',
}
if not getattr(self, 'title', None) is None:
query_params['titles'] = self.titl... |
Plain text summary of the page.
| summary | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def images(self):
'''
List of URLs of images on the page.
'''
if not getattr(self, '_images', False):
self._images = [
page['imageinfo'][0]['url']
for page in self.__continued_query({
'generator': 'images',
'gimlimit': 'max',
'prop': 'imageinfo',
... |
List of URLs of images on the page.
| images | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def coordinates(self):
'''
Tuple of Decimals in the form of (lat, lon) or None
'''
if not getattr(self, '_coordinates', False):
query_params = {
'prop': 'coordinates',
'colimit': 'max',
'titles': self.title,
}
request = _wiki_request(query_params)
if 'qu... |
Tuple of Decimals in the form of (lat, lon) or None
| coordinates | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def references(self):
'''
List of URLs of external links on a page.
May include external links within page that aren't technically cited anywhere.
'''
if not getattr(self, '_references', False):
def add_protocol(url):
return url if url.startswith('http') else 'http:' + url
self... |
List of URLs of external links on a page.
May include external links within page that aren't technically cited anywhere.
| references | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def links(self):
'''
List of titles of Wikipedia page links on a page.
.. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
'''
if not getattr(self, '_links', False):
self._links = [
link['title']
for link in self._... |
List of titles of Wikipedia page links on a page.
.. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
| links | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def sections(self):
'''
List of section titles from the table of contents on the page.
'''
if not getattr(self, '_sections', False):
query_params = {
'action': 'parse',
'prop': 'sections',
}
if not getattr(self, 'title', None) is None:
query_params["page"] = ... |
List of section titles from the table of contents on the page.
| sections | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def section(self, section_title):
'''
Get the plain text content of a section from `self.sections`.
Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string.
This is a convenience method that wraps self.content.
.. warning:: Calling `section` on a section that ha... |
Get the plain text content of a section from `self.sections`.
Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string.
This is a convenience method that wraps self.content.
.. warning:: Calling `section` on a section that has subheadings will NOT return
... | section | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def languages():
'''
List all the currently supported language prefixes (usually ISO language code).
Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests
results from.
Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes,
use `wikipedia.languages().... |
List all the currently supported language prefixes (usually ISO language code).
Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests
results from.
Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes,
use `wikipedia.languages().keys()`.
| languages | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def _wiki_request(params):
'''
Make a request to the Wikipedia API using the given search parameters.
Returns a parsed dict of the JSON response.
'''
global RATE_LIMIT_LAST_CALL
global USER_AGENT
params['format'] = 'json'
if not 'action' in params:
params['action'] = 'query'
headers = {
'Use... |
Make a request to the Wikipedia API using the given search parameters.
Returns a parsed dict of the JSON response.
| _wiki_request | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def __init__(self, guid, text, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
label: (Optional) strin... | Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
label: (Optional) string. The label of the example. This should be
... | __init__ | python | ProHiryu/bert-chinese-ner | BERT_NER.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/BERT_NER.py | MIT |
def precision(labels, predictions, num_classes, pos_indices=None,
weights=None, average='micro'):
"""Multi-class precision metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
Th... | Multi-class precision metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, ... | precision | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def recall(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro'):
"""Multi-class recall metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predict... | Multi-class recall metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, opt... | recall | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def fbeta(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro', beta=1):
"""Multi-class fbeta metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The pr... | Multi-class fbeta metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, opti... | fbeta | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def safe_div(numerator, denominator):
"""Safe division, return 0 if denominator is 0"""
numerator, denominator = tf.to_float(numerator), tf.to_float(denominator)
zeros = tf.zeros_like(numerator, dtype=numerator.dtype)
denominator_is_zero = tf.equal(denominator, zeros)
return tf.where(denominator_is_... | Safe division, return 0 if denominator is 0 | safe_div | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def pr_re_fbeta(cm, pos_indices, beta=1):
"""Uses a confusion matrix to compute precision, recall and fbeta"""
num_classes = cm.shape[0]
neg_indices = [i for i in range(num_classes) if i not in pos_indices]
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, neg_indices] = 0
diag_... | Uses a confusion matrix to compute precision, recall and fbeta | pr_re_fbeta | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def metrics_from_confusion_matrix(cm, pos_indices=None, average='micro',
beta=1):
"""Precision, Recall and F1 from the confusion matrix
Parameters
----------
cm : tf.Tensor of type tf.int32, of shape (num_classes, num_classes)
The streaming confusion matrix.
... | Precision, Recall and F1 from the confusion matrix
Parameters
----------
cm : tf.Tensor of type tf.int32, of shape (num_classes, num_classes)
The streaming confusion matrix.
pos_indices : list of int, optional
The indices of the positive classes
beta : int, optional
Weight of... | metrics_from_confusion_matrix | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def run_external_command(command: List[str], print_output: bool = True) -> str:
"""Wrapper to ease the use of calling external programs"""
process = subprocess.Popen(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, _ = process.communicate()
ret = process.wait()
if (outpu... | Wrapper to ease the use of calling external programs | run_external_command | python | Syncplay/syncplay | ci/macos_app_arch_check.py | https://github.com/Syncplay/syncplay/blob/master/ci/macos_app_arch_check.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.