body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
@commands.bot_has_permissions(manage_roles=True, send_messages=True)
@commands.before_invoke(record_usage)
@cog_ext.cog_slash(name='mute', description='Mutes a member in the server', guild_ids=[settings.get_value('guild_id')], options=[create_option(name='member', description='The member that will be muted', option_typ... | 4,410,055,446,617,635,300 | Mutes member in guild. | cogs/commands/moderation/mutes.py | mute | y0usef-2E/chiya | python | @commands.bot_has_permissions(manage_roles=True, send_messages=True)
@commands.before_invoke(record_usage)
@cog_ext.cog_slash(name='mute', description='Mutes a member in the server', guild_ids=[settings.get_value('guild_id')], options=[create_option(name='member', description='The member that will be muted', option_typ... |
@commands.bot_has_permissions(manage_roles=True, send_messages=True)
@commands.before_invoke(record_usage)
@cog_ext.cog_slash(name='unmute', description='Unmutes a member in the server', guild_ids=[settings.get_value('guild_id')], options=[create_option(name='member', description='The member that will be unmuted', opti... | 8,224,397,948,412,179,000 | Unmutes member in guild. | cogs/commands/moderation/mutes.py | unmute | y0usef-2E/chiya | python | @commands.bot_has_permissions(manage_roles=True, send_messages=True)
@commands.before_invoke(record_usage)
@cog_ext.cog_slash(name='unmute', description='Unmutes a member in the server', guild_ids=[settings.get_value('guild_id')], options=[create_option(name='member', description='The member that will be unmuted', opti... |
def _get_check_for_user(request, code):
' Return specified check if current user has access to it. '
assert request.user.is_authenticated
check = get_object_or_404(Check.objects.select_related('project'), code=code)
if request.user.is_superuser:
return (check, True)
if (request.user.id == ch... | -7,245,660,821,251,507,000 | Return specified check if current user has access to it. | hc/front/views.py | _get_check_for_user | srvz/healthchecks | python | def _get_check_for_user(request, code):
' '
assert request.user.is_authenticated
check = get_object_or_404(Check.objects.select_related('project'), code=code)
if request.user.is_superuser:
return (check, True)
if (request.user.id == check.project.owner_id):
return (check, True)
... |
def _get_channel_for_user(request, code):
' Return specified channel if current user has access to it. '
assert request.user.is_authenticated
channel = get_object_or_404(Channel.objects.select_related('project'), code=code)
if request.user.is_superuser:
return (channel, True)
if (request.use... | 4,297,122,973,497,515,000 | Return specified channel if current user has access to it. | hc/front/views.py | _get_channel_for_user | srvz/healthchecks | python | def _get_channel_for_user(request, code):
' '
assert request.user.is_authenticated
channel = get_object_or_404(Channel.objects.select_related('project'), code=code)
if request.user.is_superuser:
return (channel, True)
if (request.user.id == channel.project.owner_id):
return (channel... |
def _get_project_for_user(request, project_code):
' Check access, return (project, rw) tuple. '
project = get_object_or_404(Project, code=project_code)
if request.user.is_superuser:
return (project, True)
if (request.user.id == project.owner_id):
return (project, True)
membership = g... | 4,360,222,302,387,280,000 | Check access, return (project, rw) tuple. | hc/front/views.py | _get_project_for_user | srvz/healthchecks | python | def _get_project_for_user(request, project_code):
' '
project = get_object_or_404(Project, code=project_code)
if request.user.is_superuser:
return (project, True)
if (request.user.id == project.owner_id):
return (project, True)
membership = get_object_or_404(Member, project=project,... |
def _get_rw_project_for_user(request, project_code):
' Check access, return (project, rw) tuple. '
(project, rw) = _get_project_for_user(request, project_code)
if (not rw):
raise PermissionDenied
return project | -6,583,339,608,857,261,000 | Check access, return (project, rw) tuple. | hc/front/views.py | _get_rw_project_for_user | srvz/healthchecks | python | def _get_rw_project_for_user(request, project_code):
' '
(project, rw) = _get_project_for_user(request, project_code)
if (not rw):
raise PermissionDenied
return project |
def _refresh_last_active_date(profile):
' Update last_active_date if it is more than a day old. '
now = timezone.now()
if ((profile.last_active_date is None) or ((now - profile.last_active_date).days > 0)):
profile.last_active_date = now
profile.save() | -7,346,630,996,628,235,000 | Update last_active_date if it is more than a day old. | hc/front/views.py | _refresh_last_active_date | srvz/healthchecks | python | def _refresh_last_active_date(profile):
' '
now = timezone.now()
if ((profile.last_active_date is None) or ((now - profile.last_active_date).days > 0)):
profile.last_active_date = now
profile.save() |
def compute_average_surface_distance(seg_pred: Union[(np.ndarray, torch.Tensor)], seg_gt: Union[(np.ndarray, torch.Tensor)], label_idx: int, symmetric: bool=False, distance_metric: str='euclidean'):
'\n This function is used to compute the Average Surface Distance from `seg_pred` to `seg_gt`\n under the defau... | 4,632,578,815,613,066,000 | This function is used to compute the Average Surface Distance from `seg_pred` to `seg_gt`
under the default setting.
In addition, if sets ``symmetric = True``, the average symmetric surface distance between
these two inputs will be returned.
Args:
seg_pred: first binary or labelfield image.
seg_gt: second bina... | monai/metrics/surface_distance.py | compute_average_surface_distance | Alxaline/MONAI | python | def compute_average_surface_distance(seg_pred: Union[(np.ndarray, torch.Tensor)], seg_gt: Union[(np.ndarray, torch.Tensor)], label_idx: int, symmetric: bool=False, distance_metric: str='euclidean'):
'\n This function is used to compute the Average Surface Distance from `seg_pred` to `seg_gt`\n under the defau... |
def main():
'"options for criterion is wasserstien, h_divergence'
itertn = 1
c3_value = 0.5
for trial in range(1):
args = {'img_size': 28, 'chnnl': 1, 'lr': 0.01, 'momentum': 0.9, 'epochs': 1, 'tr_smpl': 1000, 'test_smpl': 10000, 'tsk_list': ['mnist', 'svhn', 'm_mnist'], 'grad_weight': 1, 'Trial... | 6,303,770,635,771,688,000 | "options for criterion is wasserstien, h_divergence | MTL.py | main | cjshui/AMTNN | python | def main():
itertn = 1
c3_value = 0.5
for trial in range(1):
args = {'img_size': 28, 'chnnl': 1, 'lr': 0.01, 'momentum': 0.9, 'epochs': 1, 'tr_smpl': 1000, 'test_smpl': 10000, 'tsk_list': ['mnist', 'svhn', 'm_mnist'], 'grad_weight': 1, 'Trials': trial, 'criterion': 'wasserstien', 'c3': c3_value... |
def reflection(image, axis=0):
'\n 8x8のブロックごとに離散コサイン変換された画像(以下DCT画像)を鏡像変換する.\n\n Parameters\n ----------\n image:幅と高さが8の倍数である画像を表す2次元配列. 8の倍数でない場合の動作は未定義.\n \n axis:変換する軸. defalutは`axis=0`\n\n Returns\n -------\n `image`を鏡像変換したDCT画像を表す2次元配列を返す. `image`の値は変わらない.\n\n Examples\n ------... | -5,929,522,793,636,503,000 | 8x8のブロックごとに離散コサイン変換された画像(以下DCT画像)を鏡像変換する.
Parameters
----------
image:幅と高さが8の倍数である画像を表す2次元配列. 8の倍数でない場合の動作は未定義.
axis:変換する軸. defalutは`axis=0`
Returns
-------
`image`を鏡像変換したDCT画像を表す2次元配列を返す. `image`の値は変わらない.
Examples
--------
>>> import numpy as np
>>> a = np.arange(64).reshape((8,8))
>>> a
array([[ 0, 1, 2, 3, 4... | dct_image_transform/reflection.py | reflection | kanpurin/dctimagetransform | python | def reflection(image, axis=0):
'\n 8x8のブロックごとに離散コサイン変換された画像(以下DCT画像)を鏡像変換する.\n\n Parameters\n ----------\n image:幅と高さが8の倍数である画像を表す2次元配列. 8の倍数でない場合の動作は未定義.\n \n axis:変換する軸. defalutは`axis=0`\n\n Returns\n -------\n `image`を鏡像変換したDCT画像を表す2次元配列を返す. `image`の値は変わらない.\n\n Examples\n ------... |
def __init__(self, x=0, y=0):
'Konstruktor punktu.'
self.x = x
self.y = y | -1,485,226,074,151,816,200 | Konstruktor punktu. | zadanka/l5zad4.py | __init__ | wrutkowski1000/wizualizacja-danych | python | def __init__(self, x=0, y=0):
self.x = x
self.y = y |
def get_index(dataset: Dataset, loader: Loader[(Dataset, Entity)]) -> Index[(Dataset, Entity)]:
'Load the search index for the given dataset or generate one if it does\n not exist.'
path = get_index_path(dataset)
index = Index.load(loader, path)
return index | 350,794,033,161,731,000 | Load the search index for the given dataset or generate one if it does
not exist. | opensanctions/core/index.py | get_index | alephdata/opensanctions | python | def get_index(dataset: Dataset, loader: Loader[(Dataset, Entity)]) -> Index[(Dataset, Entity)]:
'Load the search index for the given dataset or generate one if it does\n not exist.'
path = get_index_path(dataset)
index = Index.load(loader, path)
return index |
def __init__(self, downloader=None):
'Constructor. Receives an optional downloader.'
self._ready = False
self._x_forwarded_for_ip = None
self.set_downloader(downloader) | 7,054,030,604,609,068,000 | Constructor. Receives an optional downloader. | youtube_dl/extractor/common.py | __init__ | DevSecOpsGuy/youtube-dl-1 | python | def __init__(self, downloader=None):
self._ready = False
self._x_forwarded_for_ip = None
self.set_downloader(downloader) |
@classmethod
def suitable(cls, url):
'Receives a URL and returns True if suitable for this IE.'
if ('_VALID_URL_RE' not in cls.__dict__):
cls._VALID_URL_RE = re.compile(cls._VALID_URL)
return (cls._VALID_URL_RE.match(url) is not None) | -4,011,644,621,854,200,000 | Receives a URL and returns True if suitable for this IE. | youtube_dl/extractor/common.py | suitable | DevSecOpsGuy/youtube-dl-1 | python | @classmethod
def suitable(cls, url):
if ('_VALID_URL_RE' not in cls.__dict__):
cls._VALID_URL_RE = re.compile(cls._VALID_URL)
return (cls._VALID_URL_RE.match(url) is not None) |
@classmethod
def working(cls):
'Getter method for _WORKING.'
return cls._WORKING | 2,406,935,002,155,684,400 | Getter method for _WORKING. | youtube_dl/extractor/common.py | working | DevSecOpsGuy/youtube-dl-1 | python | @classmethod
def working(cls):
return cls._WORKING |
def initialize(self):
'Initializes an instance (authentication, etc).'
self._initialize_geo_bypass({'countries': self._GEO_COUNTRIES, 'ip_blocks': self._GEO_IP_BLOCKS})
if (not self._ready):
self._real_initialize()
self._ready = True | -4,230,263,112,828,807,000 | Initializes an instance (authentication, etc). | youtube_dl/extractor/common.py | initialize | DevSecOpsGuy/youtube-dl-1 | python | def initialize(self):
self._initialize_geo_bypass({'countries': self._GEO_COUNTRIES, 'ip_blocks': self._GEO_IP_BLOCKS})
if (not self._ready):
self._real_initialize()
self._ready = True |
def _initialize_geo_bypass(self, geo_bypass_context):
"\n Initialize geo restriction bypass mechanism.\n\n This method is used to initialize geo bypass mechanism based on faking\n X-Forwarded-For HTTP header. A random country from provided country list\n is selected and a random IP belon... | -8,957,561,630,360,193,000 | Initialize geo restriction bypass mechanism.
This method is used to initialize geo bypass mechanism based on faking
X-Forwarded-For HTTP header. A random country from provided country list
is selected and a random IP belonging to this country is generated. This
IP will be passed as X-Forwarded-For HTTP header in all s... | youtube_dl/extractor/common.py | _initialize_geo_bypass | DevSecOpsGuy/youtube-dl-1 | python | def _initialize_geo_bypass(self, geo_bypass_context):
"\n Initialize geo restriction bypass mechanism.\n\n This method is used to initialize geo bypass mechanism based on faking\n X-Forwarded-For HTTP header. A random country from provided country list\n is selected and a random IP belon... |
def extract(self, url):
'Extracts URL information and returns it in list of dicts.'
try:
for _ in range(2):
try:
self.initialize()
ie_result = self._real_extract(url)
if self._x_forwarded_for_ip:
ie_result['__x_forwarded_for... | -5,138,944,494,329,492,000 | Extracts URL information and returns it in list of dicts. | youtube_dl/extractor/common.py | extract | DevSecOpsGuy/youtube-dl-1 | python | def extract(self, url):
try:
for _ in range(2):
try:
self.initialize()
ie_result = self._real_extract(url)
if self._x_forwarded_for_ip:
ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
return ie_... |
def set_downloader(self, downloader):
'Sets the downloader for this IE.'
self._downloader = downloader | -6,028,627,441,873,874,000 | Sets the downloader for this IE. | youtube_dl/extractor/common.py | set_downloader | DevSecOpsGuy/youtube-dl-1 | python | def set_downloader(self, downloader):
self._downloader = downloader |
def _real_initialize(self):
'Real initialization process. Redefine in subclasses.'
pass | -1,551,871,763,434,820,600 | Real initialization process. Redefine in subclasses. | youtube_dl/extractor/common.py | _real_initialize | DevSecOpsGuy/youtube-dl-1 | python | def _real_initialize(self):
pass |
def _real_extract(self, url):
'Real extraction process. Redefine in subclasses.'
pass | 9,121,875,136,483,058,000 | Real extraction process. Redefine in subclasses. | youtube_dl/extractor/common.py | _real_extract | DevSecOpsGuy/youtube-dl-1 | python | def _real_extract(self, url):
pass |
@classmethod
def ie_key(cls):
'A string for getting the InfoExtractor with get_info_extractor'
return compat_str(cls.__name__[:(- 2)]) | 5,437,829,511,205,614,000 | A string for getting the InfoExtractor with get_info_extractor | youtube_dl/extractor/common.py | ie_key | DevSecOpsGuy/youtube-dl-1 | python | @classmethod
def ie_key(cls):
return compat_str(cls.__name__[:(- 2)]) |
def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None, headers={}, query={}, expected_status=None):
'\n Return the response handle.\n\n See _download_webpage docstring for arguments specification.\n '
if (note is None):
self.report_downl... | 4,311,339,888,729,569,300 | Return the response handle.
See _download_webpage docstring for arguments specification. | youtube_dl/extractor/common.py | _request_webpage | DevSecOpsGuy/youtube-dl-1 | python | def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None, headers={}, query={}, expected_status=None):
'\n Return the response handle.\n\n See _download_webpage docstring for arguments specification.\n '
if (note is None):
self.report_downl... |
def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return a tuple (page content as string, URL handle).\n\n See _download_webpage docstring for arguments specification.\n '
... | 7,614,932,583,454,537,000 | Return a tuple (page content as string, URL handle).
See _download_webpage docstring for arguments specification. | youtube_dl/extractor/common.py | _download_webpage_handle | DevSecOpsGuy/youtube-dl-1 | python | def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return a tuple (page content as string, URL handle).\n\n See _download_webpage docstring for arguments specification.\n '
... |
def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return the data of the page as a string.\n\n Arguments:\n url_or_request -- plain text URL as a string or\n ... | 8,941,889,573,552,861,000 | Return the data of the page as a string.
Arguments:
url_or_request -- plain text URL as a string or
a compat_urllib_request.Requestobject
video_id -- Video/playlist/item identifier (string)
Keyword arguments:
note -- note printed before downloading (string)
errnote -- note printed in case of an error (string)
fat... | youtube_dl/extractor/common.py | _download_webpage | DevSecOpsGuy/youtube-dl-1 | python | def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return the data of the page as a string.\n\n Arguments:\n url_or_request -- plain text URL as a string or\n ... |
def _download_xml_handle(self, url_or_request, video_id, note='Downloading XML', errnote='Unable to download XML', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return a tuple (xml as an compat_etree_Element, URL handle).\n\n See _downloa... | -2,285,998,260,765,022,200 | Return a tuple (xml as an compat_etree_Element, URL handle).
See _download_webpage docstring for arguments specification. | youtube_dl/extractor/common.py | _download_xml_handle | DevSecOpsGuy/youtube-dl-1 | python | def _download_xml_handle(self, url_or_request, video_id, note='Downloading XML', errnote='Unable to download XML', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return a tuple (xml as an compat_etree_Element, URL handle).\n\n See _downloa... |
def _download_xml(self, url_or_request, video_id, note='Downloading XML', errnote='Unable to download XML', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return the xml as an compat_etree_Element.\n\n See _download_webpage docstring for a... | -2,794,144,738,840,244,000 | Return the xml as an compat_etree_Element.
See _download_webpage docstring for arguments specification. | youtube_dl/extractor/common.py | _download_xml | DevSecOpsGuy/youtube-dl-1 | python | def _download_xml(self, url_or_request, video_id, note='Downloading XML', errnote='Unable to download XML', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return the xml as an compat_etree_Element.\n\n See _download_webpage docstring for a... |
def _download_json_handle(self, url_or_request, video_id, note='Downloading JSON metadata', errnote='Unable to download JSON metadata', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return a tuple (JSON object, URL handle).\n\n See _downl... | -7,486,056,734,759,543,000 | Return a tuple (JSON object, URL handle).
See _download_webpage docstring for arguments specification. | youtube_dl/extractor/common.py | _download_json_handle | DevSecOpsGuy/youtube-dl-1 | python | def _download_json_handle(self, url_or_request, video_id, note='Downloading JSON metadata', errnote='Unable to download JSON metadata', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return a tuple (JSON object, URL handle).\n\n See _downl... |
def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata', errnote='Unable to download JSON metadata', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return the JSON object as a dict.\n\n See _download_webpage doc... | 6,550,132,766,695,574,000 | Return the JSON object as a dict.
See _download_webpage docstring for arguments specification. | youtube_dl/extractor/common.py | _download_json | DevSecOpsGuy/youtube-dl-1 | python | def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata', errnote='Unable to download JSON metadata', transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
'\n Return the JSON object as a dict.\n\n See _download_webpage doc... |
def to_screen(self, msg):
"Print msg to screen, prefixing it with '[ie_name]'"
self._downloader.to_screen(('[%s] %s' % (self.IE_NAME, msg))) | -8,257,251,742,180,446,000 | Print msg to screen, prefixing it with '[ie_name]' | youtube_dl/extractor/common.py | to_screen | DevSecOpsGuy/youtube-dl-1 | python | def to_screen(self, msg):
self._downloader.to_screen(('[%s] %s' % (self.IE_NAME, msg))) |
def report_extraction(self, id_or_name):
'Report information extraction.'
self.to_screen(('%s: Extracting information' % id_or_name)) | 9,209,310,315,850,801,000 | Report information extraction. | youtube_dl/extractor/common.py | report_extraction | DevSecOpsGuy/youtube-dl-1 | python | def report_extraction(self, id_or_name):
self.to_screen(('%s: Extracting information' % id_or_name)) |
def report_download_webpage(self, video_id):
'Report webpage download.'
self.to_screen(('%s: Downloading webpage' % video_id)) | -7,977,462,286,677,206,000 | Report webpage download. | youtube_dl/extractor/common.py | report_download_webpage | DevSecOpsGuy/youtube-dl-1 | python | def report_download_webpage(self, video_id):
self.to_screen(('%s: Downloading webpage' % video_id)) |
def report_age_confirmation(self):
'Report attempt to confirm age.'
self.to_screen('Confirming age') | 5,554,603,744,244,092,000 | Report attempt to confirm age. | youtube_dl/extractor/common.py | report_age_confirmation | DevSecOpsGuy/youtube-dl-1 | python | def report_age_confirmation(self):
self.to_screen('Confirming age') |
def report_login(self):
'Report attempt to log in.'
self.to_screen('Logging in') | -2,843,299,703,482,748,000 | Report attempt to log in. | youtube_dl/extractor/common.py | report_login | DevSecOpsGuy/youtube-dl-1 | python | def report_login(self):
self.to_screen('Logging in') |
@staticmethod
def url_result(url, ie=None, video_id=None, video_title=None):
'Returns a URL that points to a page that should be processed'
video_info = {'_type': 'url', 'url': url, 'ie_key': ie}
if (video_id is not None):
video_info['id'] = video_id
if (video_title is not None):
video_i... | 2,635,067,718,620,197,000 | Returns a URL that points to a page that should be processed | youtube_dl/extractor/common.py | url_result | DevSecOpsGuy/youtube-dl-1 | python | @staticmethod
def url_result(url, ie=None, video_id=None, video_title=None):
video_info = {'_type': 'url', 'url': url, 'ie_key': ie}
if (video_id is not None):
video_info['id'] = video_id
if (video_title is not None):
video_info['title'] = video_title
return video_info |
@staticmethod
def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
'Returns a playlist'
video_info = {'_type': 'playlist', 'entries': entries}
if playlist_id:
video_info['id'] = playlist_id
if playlist_title:
video_info['title'] = playlist_title... | -8,882,779,261,970,664,000 | Returns a playlist | youtube_dl/extractor/common.py | playlist_result | DevSecOpsGuy/youtube-dl-1 | python | @staticmethod
def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
video_info = {'_type': 'playlist', 'entries': entries}
if playlist_id:
video_info['id'] = playlist_id
if playlist_title:
video_info['title'] = playlist_title
if playlist_des... |
def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
'\n Perform a regex search on the given string, using a single or a list of\n patterns returning the first matching group.\n In case of failure return a default value or raise a WARNING or a\n ... | 9,130,158,884,569,310,000 | Perform a regex search on the given string, using a single or a list of
patterns returning the first matching group.
In case of failure return a default value or raise a WARNING or a
RegexNotFoundError, depending on fatal, specifying the field name. | youtube_dl/extractor/common.py | _search_regex | DevSecOpsGuy/youtube-dl-1 | python | def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
'\n Perform a regex search on the given string, using a single or a list of\n patterns returning the first matching group.\n In case of failure return a default value or raise a WARNING or a\n ... |
def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
'\n Like _search_regex, but strips HTML tags and unescapes entities.\n '
res = self._search_regex(pattern, string, name, default, fatal, flags, group)
if res:
return clean_html(res... | 8,618,604,773,723,527,000 | Like _search_regex, but strips HTML tags and unescapes entities. | youtube_dl/extractor/common.py | _html_search_regex | DevSecOpsGuy/youtube-dl-1 | python | def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
'\n \n '
res = self._search_regex(pattern, string, name, default, fatal, flags, group)
if res:
return clean_html(res).strip()
else:
return res |
def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
"\n Get the login info as (username, password)\n First look for the manually specified credentials using username_option\n and password_option as keys in params dictionary. If no such credenti... | -4,727,685,870,909,069,000 | Get the login info as (username, password)
First look for the manually specified credentials using username_option
and password_option as keys in params dictionary. If no such credentials
available look in the netrc file using the netrc_machine or _NETRC_MACHINE
value.
If there's no info available, return (None, None) | youtube_dl/extractor/common.py | _get_login_info | DevSecOpsGuy/youtube-dl-1 | python | def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
"\n Get the login info as (username, password)\n First look for the manually specified credentials using username_option\n and password_option as keys in params dictionary. If no such credenti... |
def _get_tfa_info(self, note='two-factor verification code'):
"\n Get the two-factor authentication info\n TODO - asking the user will be required for sms/phone verify\n currently just uses the command line option\n If there's no info available, return None\n "
if (self._downl... | -1,595,709,114,444,867,000 | Get the two-factor authentication info
TODO - asking the user will be required for sms/phone verify
currently just uses the command line option
If there's no info available, return None | youtube_dl/extractor/common.py | _get_tfa_info | DevSecOpsGuy/youtube-dl-1 | python | def _get_tfa_info(self, note='two-factor verification code'):
"\n Get the two-factor authentication info\n TODO - asking the user will be required for sms/phone verify\n currently just uses the command line option\n If there's no info available, return None\n "
if (self._downl... |
def http_scheme(self):
' Either "http:" or "https:", depending on the user\'s preferences '
return ('http:' if self._downloader.params.get('prefer_insecure', False) else 'https:') | -2,735,384,092,449,529,300 | Either "http:" or "https:", depending on the user's preferences | youtube_dl/extractor/common.py | http_scheme | DevSecOpsGuy/youtube-dl-1 | python | def http_scheme(self):
' Either "http:" or "https:", depending on the user\'s preferences '
return ('http:' if self._downloader.params.get('prefer_insecure', False) else 'https:') |
def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}, mpd_url=None):
'\n Parse formats from MPD manifest.\n References:\n 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),\n http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1... | 7,961,288,481,499,288,000 | Parse formats from MPD manifest.
References:
1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP | youtube_dl/extractor/common.py | _parse_mpd_formats | DevSecOpsGuy/youtube-dl-1 | python | def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url=, formats_dict={}, mpd_url=None):
'\n Parse formats from MPD manifest.\n References:\n 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),\n http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2... |
def _parse_ism_formats(self, ism_doc, ism_url, ism_id=None):
'\n Parse formats from ISM manifest.\n References:\n 1. [MS-SSTR]: Smooth Streaming Protocol,\n https://msdn.microsoft.com/en-us/library/ff469518.aspx\n '
if ((ism_doc.get('IsLive') == 'TRUE') or (ism_doc.find('... | -2,052,320,450,133,081,300 | Parse formats from ISM manifest.
References:
1. [MS-SSTR]: Smooth Streaming Protocol,
https://msdn.microsoft.com/en-us/library/ff469518.aspx | youtube_dl/extractor/common.py | _parse_ism_formats | DevSecOpsGuy/youtube-dl-1 | python | def _parse_ism_formats(self, ism_doc, ism_url, ism_id=None):
'\n Parse formats from ISM manifest.\n References:\n 1. [MS-SSTR]: Smooth Streaming Protocol,\n https://msdn.microsoft.com/en-us/library/ff469518.aspx\n '
if ((ism_doc.get('IsLive') == 'TRUE') or (ism_doc.find('... |
def _live_title(self, name):
' Generate the title for a live video '
now = datetime.datetime.now()
now_str = now.strftime('%Y-%m-%d %H:%M')
return ((name + ' ') + now_str) | 1,526,277,538,303,499,000 | Generate the title for a live video | youtube_dl/extractor/common.py | _live_title | DevSecOpsGuy/youtube-dl-1 | python | def _live_title(self, name):
' '
now = datetime.datetime.now()
now_str = now.strftime('%Y-%m-%d %H:%M')
return ((name + ' ') + now_str) |
def _get_cookies(self, url):
' Return a compat_cookies.SimpleCookie with the cookies for the url '
req = sanitized_Request(url)
self._downloader.cookiejar.add_cookie_header(req)
return compat_cookies.SimpleCookie(req.get_header('Cookie')) | 192,552,671,788,474,620 | Return a compat_cookies.SimpleCookie with the cookies for the url | youtube_dl/extractor/common.py | _get_cookies | DevSecOpsGuy/youtube-dl-1 | python | def _get_cookies(self, url):
' '
req = sanitized_Request(url)
self._downloader.cookiejar.add_cookie_header(req)
return compat_cookies.SimpleCookie(req.get_header('Cookie')) |
def _apply_first_set_cookie_header(self, url_handle, cookie):
'\n Apply first Set-Cookie header instead of the last. Experimental.\n\n Some sites (e.g. [1-3]) may serve two cookies under the same name\n in Set-Cookie header and expect the first (old) one to be set rather\n than second (n... | -3,143,821,134,783,491,000 | Apply first Set-Cookie header instead of the last. Experimental.
Some sites (e.g. [1-3]) may serve two cookies under the same name
in Set-Cookie header and expect the first (old) one to be set rather
than second (new). However, as of RFC6265 the newer one cookie
should be set into cookie store what actually happens.
W... | youtube_dl/extractor/common.py | _apply_first_set_cookie_header | DevSecOpsGuy/youtube-dl-1 | python | def _apply_first_set_cookie_header(self, url_handle, cookie):
'\n Apply first Set-Cookie header instead of the last. Experimental.\n\n Some sites (e.g. [1-3]) may serve two cookies under the same name\n in Set-Cookie header and expect the first (old) one to be set rather\n than second (n... |
def is_suitable(self, age_limit):
' Test whether the extractor is generally suitable for the given\n age limit (i.e. pornographic sites are not, all others usually are) '
any_restricted = False
for tc in self.get_testcases(include_onlymatching=False):
if tc.get('playlist', []):
tc... | -8,900,054,884,063,124,000 | Test whether the extractor is generally suitable for the given
age limit (i.e. pornographic sites are not, all others usually are) | youtube_dl/extractor/common.py | is_suitable | DevSecOpsGuy/youtube-dl-1 | python | def is_suitable(self, age_limit):
' Test whether the extractor is generally suitable for the given\n age limit (i.e. pornographic sites are not, all others usually are) '
any_restricted = False
for tc in self.get_testcases(include_onlymatching=False):
if tc.get('playlist', []):
tc... |
@staticmethod
def _merge_subtitle_items(subtitle_list1, subtitle_list2):
' Merge subtitle items for one language. Items with duplicated URLs\n will be dropped. '
list1_urls = set([item['url'] for item in subtitle_list1])
ret = list(subtitle_list1)
ret.extend([item for item in subtitle_list2 if (i... | -8,306,789,552,558,350,000 | Merge subtitle items for one language. Items with duplicated URLs
will be dropped. | youtube_dl/extractor/common.py | _merge_subtitle_items | DevSecOpsGuy/youtube-dl-1 | python | @staticmethod
def _merge_subtitle_items(subtitle_list1, subtitle_list2):
' Merge subtitle items for one language. Items with duplicated URLs\n will be dropped. '
list1_urls = set([item['url'] for item in subtitle_list1])
ret = list(subtitle_list1)
ret.extend([item for item in subtitle_list2 if (i... |
@classmethod
def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
' Merge two subtitle dictionaries, language by language. '
ret = dict(subtitle_dict1)
for lang in subtitle_dict2:
ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
return ret | -8,135,354,963,678,094,000 | Merge two subtitle dictionaries, language by language. | youtube_dl/extractor/common.py | _merge_subtitles | DevSecOpsGuy/youtube-dl-1 | python | @classmethod
def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
' '
ret = dict(subtitle_dict1)
for lang in subtitle_dict2:
ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
return ret |
def _get_n_results(self, query, n):
'Get a specified number of results for a query'
raise NotImplementedError('This method must be implemented by subclasses') | -6,232,748,535,575,834,000 | Get a specified number of results for a query | youtube_dl/extractor/common.py | _get_n_results | DevSecOpsGuy/youtube-dl-1 | python | def _get_n_results(self, query, n):
raise NotImplementedError('This method must be implemented by subclasses') |
def __init__(self, client, **kwargs):
'\n Creates a new TransferDeviceClientCompositeOperations object\n\n :param TransferDeviceClient client:\n The service client which will be wrapped by this object\n '
self.client = client | 3,272,872,751,382,135,300 | Creates a new TransferDeviceClientCompositeOperations object
:param TransferDeviceClient client:
The service client which will be wrapped by this object | src/oci/dts/transfer_device_client_composite_operations.py | __init__ | CentroidChef/oci-python-sdk | python | def __init__(self, client, **kwargs):
'\n Creates a new TransferDeviceClientCompositeOperations object\n\n :param TransferDeviceClient client:\n The service client which will be wrapped by this object\n '
self.client = client |
def update_transfer_device_and_wait_for_state(self, id, transfer_device_label, update_transfer_device_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
'\n Calls :py:func:`~oci.dts.TransferDeviceClient.update_transfer_device` and waits for the :py:class:`~oci.dts.models.TransferDevice` act... | -2,558,973,560,206,875,000 | Calls :py:func:`~oci.dts.TransferDeviceClient.update_transfer_device` and waits for the :py:class:`~oci.dts.models.TransferDevice` acted upon
to enter the given state(s).
:param str id: (required)
ID of the Transfer Job
:param str transfer_device_label: (required)
Label of the Transfer Device
:param oci.dts.... | src/oci/dts/transfer_device_client_composite_operations.py | update_transfer_device_and_wait_for_state | CentroidChef/oci-python-sdk | python | def update_transfer_device_and_wait_for_state(self, id, transfer_device_label, update_transfer_device_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
'\n Calls :py:func:`~oci.dts.TransferDeviceClient.update_transfer_device` and waits for the :py:class:`~oci.dts.models.TransferDevice` act... |
def do_plots_c(Ud, Unew):
' plot Ud,new and Ud with zoom on the bug '
pylab.clf()
pylab.cla()
f = pylab.figure()
f.text(0.5, 0.95, '$U_{\\rm d}$ (left) and $U_{\\rm d, new}$ (right) ', horizontalalignment='center')
pylab.subplot(221)
pylab.imshow(Ud[0])
pylab.ylabel('# of cells', size=8)... | -4,154,372,507,956,683,300 | plot Ud,new and Ud with zoom on the bug | homework5_elliptic_PDES/part_c.py | do_plots_c | aquario-crypto/Numerical_Methods_for_Physics | python | def do_plots_c(Ud, Unew):
' '
pylab.clf()
pylab.cla()
f = pylab.figure()
f.text(0.5, 0.95, '$U_{\\rm d}$ (left) and $U_{\\rm d, new}$ (right) ', horizontalalignment='center')
pylab.subplot(221)
pylab.imshow(Ud[0])
pylab.ylabel('# of cells', size=8)
pylab.subplot(223)
pylab.imsho... |
def doPartC(Ustar, phi_num, Ud, nx, ny, xmin, xmax, ymin, ymax, DO_PLOTS):
' coordinates of centers '
dx = ((xmax - xmin) / nx)
dy = ((ymax - ymin) / ny)
' calcuates the new gradient'
Gphi = numpy.gradient(phi_num, dx, dy)
' recover Ud, new '
Unew = map(operator.sub, Ustar, Gphi)
if (DO_... | 1,935,657,053,746,374,100 | coordinates of centers | homework5_elliptic_PDES/part_c.py | doPartC | aquario-crypto/Numerical_Methods_for_Physics | python | def doPartC(Ustar, phi_num, Ud, nx, ny, xmin, xmax, ymin, ymax, DO_PLOTS):
' '
dx = ((xmax - xmin) / nx)
dy = ((ymax - ymin) / ny)
' calcuates the new gradient'
Gphi = numpy.gradient(phi_num, dx, dy)
' recover Ud, new '
Unew = map(operator.sub, Ustar, Gphi)
if (DO_PLOTS == 1):
d... |
@ingredient.config
def cfg():
'Model configuration.'
name = ''
parameters = {} | 8,649,613,754,139,806,000 | Model configuration. | exp/ingredients/model.py | cfg | BorgwardtLab/topo-ae-distances | python | @ingredient.config
def cfg():
name =
parameters = {} |
@ingredient.named_config
def TopologicalSurrogateAutoencoder():
'TopologicalSurrogateAutoencoder.'
name = 'TopologicalSurrogateAutoencoder'
parameters = {'d_latent': ((8 * 2) * 2), 'batch_size': 32, 'arch': [256, 256, 256, 256]} | 255,811,074,982,332,700 | TopologicalSurrogateAutoencoder. | exp/ingredients/model.py | TopologicalSurrogateAutoencoder | BorgwardtLab/topo-ae-distances | python | @ingredient.named_config
def TopologicalSurrogateAutoencoder():
name = 'TopologicalSurrogateAutoencoder'
parameters = {'d_latent': ((8 * 2) * 2), 'batch_size': 32, 'arch': [256, 256, 256, 256]} |
@ingredient.capture
def get_instance(name, parameters, _log, _seed):
'Get an instance of a model according to parameters in the configuration.\n\n Also, check if the provided parameters fit to the signature of the model\n class and log default values if not defined via the configuration.\n\n '
model_cl... | -27,743,696,695,635,120 | Get an instance of a model according to parameters in the configuration.
Also, check if the provided parameters fit to the signature of the model
class and log default values if not defined via the configuration. | exp/ingredients/model.py | get_instance | BorgwardtLab/topo-ae-distances | python | @ingredient.capture
def get_instance(name, parameters, _log, _seed):
'Get an instance of a model according to parameters in the configuration.\n\n Also, check if the provided parameters fit to the signature of the model\n class and log default values if not defined via the configuration.\n\n '
model_cl... |
def get_conn(self):
'\n Retrieves connection to Cloud Translate\n\n :return: Google Cloud Translate client object.\n :rtype: Client\n '
if (not self._client):
self._client = Client(credentials=self._get_credentials())
return self._client | 8,639,950,463,497,811,000 | Retrieves connection to Cloud Translate
:return: Google Cloud Translate client object.
:rtype: Client | airflow/contrib/hooks/gcp_translate_hook.py | get_conn | CatarinaSilva/airflow | python | def get_conn(self):
'\n Retrieves connection to Cloud Translate\n\n :return: Google Cloud Translate client object.\n :rtype: Client\n '
if (not self._client):
self._client = Client(credentials=self._get_credentials())
return self._client |
def translate(self, values, target_language, format_=None, source_language=None, model=None):
"Translate a string or list of strings.\n\n See https://cloud.google.com/translate/docs/translating-text\n\n :type values: str or list\n :param values: String or list of strings to translate.\n ... | -4,404,416,656,389,028,400 | Translate a string or list of strings.
See https://cloud.google.com/translate/docs/translating-text
:type values: str or list
:param values: String or list of strings to translate.
:type target_language: str
:param target_language: The language to translate results into. This
is required by th... | airflow/contrib/hooks/gcp_translate_hook.py | translate | CatarinaSilva/airflow | python | def translate(self, values, target_language, format_=None, source_language=None, model=None):
"Translate a string or list of strings.\n\n See https://cloud.google.com/translate/docs/translating-text\n\n :type values: str or list\n :param values: String or list of strings to translate.\n ... |
@testing.requires_testing_data
def test_field_map_ctf():
'Test that field mapping can be done with CTF data.'
raw = read_raw_fif(raw_ctf_fname).crop(0, 1)
raw.apply_gradient_compensation(3)
events = make_fixed_length_events(raw, duration=0.5)
evoked = Epochs(raw, events).average()
evoked.pick_ch... | 3,898,756,881,485,746,000 | Test that field mapping can be done with CTF data. | mne/forward/tests/test_field_interpolation.py | test_field_map_ctf | 0reza/mne-python | python | @testing.requires_testing_data
def test_field_map_ctf():
raw = read_raw_fif(raw_ctf_fname).crop(0, 1)
raw.apply_gradient_compensation(3)
events = make_fixed_length_events(raw, duration=0.5)
evoked = Epochs(raw, events).average()
evoked.pick_channels(evoked.ch_names[:50])
make_field_map(evok... |
def test_legendre_val():
'Test Legendre polynomial (derivative) equivalence.'
rng = np.random.RandomState(0)
xs = np.linspace((- 1.0), 1.0, 1000)
n_terms = 100
vals_np = legendre.legvander(xs, (n_terms - 1))
for (nc, interp) in zip([100, 50], ['nearest', 'linear']):
(lut, n_fact) = _get_... | 4,881,300,242,660,246,000 | Test Legendre polynomial (derivative) equivalence. | mne/forward/tests/test_field_interpolation.py | test_legendre_val | 0reza/mne-python | python | def test_legendre_val():
rng = np.random.RandomState(0)
xs = np.linspace((- 1.0), 1.0, 1000)
n_terms = 100
vals_np = legendre.legvander(xs, (n_terms - 1))
for (nc, interp) in zip([100, 50], ['nearest', 'linear']):
(lut, n_fact) = _get_legen_table('eeg', n_coeff=nc, force_calc=True)
... |
def test_legendre_table():
'Test Legendre table calculation.'
n = 10
for ch_type in ['eeg', 'meg']:
(lut1, n_fact1) = _get_legen_table(ch_type, n_coeff=25, force_calc=True)
lut1 = lut1[:, :(n - 1)].copy()
n_fact1 = n_fact1[:(n - 1)].copy()
(lut2, n_fact2) = _get_legen_table(c... | -3,882,972,427,821,506,600 | Test Legendre table calculation. | mne/forward/tests/test_field_interpolation.py | test_legendre_table | 0reza/mne-python | python | def test_legendre_table():
n = 10
for ch_type in ['eeg', 'meg']:
(lut1, n_fact1) = _get_legen_table(ch_type, n_coeff=25, force_calc=True)
lut1 = lut1[:, :(n - 1)].copy()
n_fact1 = n_fact1[:(n - 1)].copy()
(lut2, n_fact2) = _get_legen_table(ch_type, n_coeff=n, force_calc=True... |
@testing.requires_testing_data
def test_make_field_map_eeg():
'Test interpolation of EEG field onto head.'
evoked = read_evokeds(evoked_fname, condition='Left Auditory')
evoked.info['bads'] = ['MEG 2443', 'EEG 053']
surf = get_head_surf('sample', subjects_dir=subjects_dir)
pytest.raises(ValueError, ... | -1,162,614,805,405,947,000 | Test interpolation of EEG field onto head. | mne/forward/tests/test_field_interpolation.py | test_make_field_map_eeg | 0reza/mne-python | python | @testing.requires_testing_data
def test_make_field_map_eeg():
evoked = read_evokeds(evoked_fname, condition='Left Auditory')
evoked.info['bads'] = ['MEG 2443', 'EEG 053']
surf = get_head_surf('sample', subjects_dir=subjects_dir)
pytest.raises(ValueError, _make_surface_mapping, evoked.info, surf, 'e... |
@testing.requires_testing_data
@pytest.mark.slowtest
def test_make_field_map_meg():
'Test interpolation of MEG field onto helmet | head.'
evoked = read_evokeds(evoked_fname, condition='Left Auditory')
info = evoked.info
surf = get_meg_helmet_surf(info)
info['bads'] = info['ch_names'][:200]
pytes... | -6,780,296,683,290,353,000 | Test interpolation of MEG field onto helmet | head. | mne/forward/tests/test_field_interpolation.py | test_make_field_map_meg | 0reza/mne-python | python | @testing.requires_testing_data
@pytest.mark.slowtest
def test_make_field_map_meg():
evoked = read_evokeds(evoked_fname, condition='Left Auditory')
info = evoked.info
surf = get_meg_helmet_surf(info)
info['bads'] = info['ch_names'][:200]
pytest.raises(ValueError, _make_surface_mapping, info, sur... |
@testing.requires_testing_data
def test_make_field_map_meeg():
'Test making a M/EEG field map onto helmet & head.'
evoked = read_evokeds(evoked_fname, baseline=((- 0.2), 0.0))[0]
picks = pick_types(evoked.info, meg=True, eeg=True)
picks = picks[::10]
evoked.pick_channels([evoked.ch_names[p] for p in... | 5,279,945,788,715,939,000 | Test making a M/EEG field map onto helmet & head. | mne/forward/tests/test_field_interpolation.py | test_make_field_map_meeg | 0reza/mne-python | python | @testing.requires_testing_data
def test_make_field_map_meeg():
evoked = read_evokeds(evoked_fname, baseline=((- 0.2), 0.0))[0]
picks = pick_types(evoked.info, meg=True, eeg=True)
picks = picks[::10]
evoked.pick_channels([evoked.ch_names[p] for p in picks])
evoked.info.normalize_proj()
maps ... |
def _setup_args(info):
'Configure args for test_as_meg_type_evoked.'
coils = _create_meg_coils(info['chs'], 'normal', info['dev_head_t'])
(int_rad, _, lut_fun, n_fact) = _setup_dots('fast', info, coils, 'meg')
my_origin = np.array([0.0, 0.0, 0.04])
args_dict = dict(intrad=int_rad, volume=False, coil... | 7,179,594,168,567,113,000 | Configure args for test_as_meg_type_evoked. | mne/forward/tests/test_field_interpolation.py | _setup_args | 0reza/mne-python | python | def _setup_args(info):
coils = _create_meg_coils(info['chs'], 'normal', info['dev_head_t'])
(int_rad, _, lut_fun, n_fact) = _setup_dots('fast', info, coils, 'meg')
my_origin = np.array([0.0, 0.0, 0.04])
args_dict = dict(intrad=int_rad, volume=False, coils1=coils, r0=my_origin, ch_type='meg', lut=lu... |
@testing.requires_testing_data
def test_as_meg_type_evoked():
'Test interpolation of data on to virtual channels.'
raw = read_raw_fif(raw_fname)
events = mne.find_events(raw)
picks = pick_types(raw.info, meg=True, eeg=True, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads')
epochs =... | 5,587,401,729,087,093,000 | Test interpolation of data on to virtual channels. | mne/forward/tests/test_field_interpolation.py | test_as_meg_type_evoked | 0reza/mne-python | python | @testing.requires_testing_data
def test_as_meg_type_evoked():
raw = read_raw_fif(raw_fname)
events = mne.find_events(raw)
picks = pick_types(raw.info, meg=True, eeg=True, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads')
epochs = mne.Epochs(raw, events, picks=picks)
evoked = e... |
def dist_kl(p: Prob, q: Prob):
'Kullback-Leibler divergence between two probability distributions.'
kl_div = (p.p * (np.log((p.p + (p == 0))) - np.log((q.p + (p.p == 0)))))
return np.sum(kl_div) | -8,010,159,052,281,958,000 | Kullback-Leibler divergence between two probability distributions. | inferlo/generic/libdai_bp.py | dist_kl | InferLO/inferlo | python | def dist_kl(p: Prob, q: Prob):
kl_div = (p.p * (np.log((p.p + (p == 0))) - np.log((q.p + (p.p == 0)))))
return np.sum(kl_div) |
def dist_linf(p: Prob, q: Prob):
'Distance between two probability distributions in L_infinity norm.'
return np.max(np.abs((p.p - q.p))) | 5,676,502,167,310,320,000 | Distance between two probability distributions in L_infinity norm. | inferlo/generic/libdai_bp.py | dist_linf | InferLO/inferlo | python | def dist_linf(p: Prob, q: Prob):
return np.max(np.abs((p.p - q.p))) |
@staticmethod
def uniform(n):
'Creates unifom probability distribution.'
return Prob.same_value(n, (1.0 / n)) | -4,663,781,209,296,906,000 | Creates unifom probability distribution. | inferlo/generic/libdai_bp.py | uniform | InferLO/inferlo | python | @staticmethod
def uniform(n):
return Prob.same_value(n, (1.0 / n)) |
@staticmethod
def same_value(n: int, val: float):
'Creates vector filled with the same value.'
return Prob((np.ones(n, dtype=np.float64) * val)) | 681,741,583,617,377,800 | Creates vector filled with the same value. | inferlo/generic/libdai_bp.py | same_value | InferLO/inferlo | python | @staticmethod
def same_value(n: int, val: float):
return Prob((np.ones(n, dtype=np.float64) * val)) |
def fill(self, x):
'Sets all entries to x.'
self.p = (np.ones_like(self.p) * x) | 1,609,897,422,729,735,000 | Sets all entries to x. | inferlo/generic/libdai_bp.py | fill | InferLO/inferlo | python | def fill(self, x):
self.p = (np.ones_like(self.p) * x) |
def clone(self):
'Makes a copy.'
return Prob(np.array(self.p)) | 8,396,041,533,749,117,000 | Makes a copy. | inferlo/generic/libdai_bp.py | clone | InferLO/inferlo | python | def clone(self):
return Prob(np.array(self.p)) |
def normalize(self):
'Normalize distribution.'
self.p /= np.sum(self.p) | 6,639,159,798,546,026,000 | Normalize distribution. | inferlo/generic/libdai_bp.py | normalize | InferLO/inferlo | python | def normalize(self):
self.p /= np.sum(self.p) |
def entropy(self) -> float:
'Calculate entropy of the distribution.'
return (- np.sum((self.p * np.log(self.p)))) | -1,429,585,937,468,360,000 | Calculate entropy of the distribution. | inferlo/generic/libdai_bp.py | entropy | InferLO/inferlo | python | def entropy(self) -> float:
return (- np.sum((self.p * np.log(self.p)))) |
@staticmethod
def uniform(model: GraphModel, var_idx: List[int]):
'Creates factor defining uniform distribution.'
total_domain_size = 1
for i in var_idx:
total_domain_size *= model.get_variable(i).domain.size()
return LDFactor(model, var_idx, Prob.uniform(total_domain_size)) | -8,068,446,661,493,057,000 | Creates factor defining uniform distribution. | inferlo/generic/libdai_bp.py | uniform | InferLO/inferlo | python | @staticmethod
def uniform(model: GraphModel, var_idx: List[int]):
total_domain_size = 1
for i in var_idx:
total_domain_size *= model.get_variable(i).domain.size()
return LDFactor(model, var_idx, Prob.uniform(total_domain_size)) |
@staticmethod
def from_inferlo_factor(f: DiscreteFactor):
'Converts inferlo.DiscreteFactor to LDFactor.'
rev_perm = list(range(len(f.var_idx)))[::(- 1)]
prob = f.values.transpose(rev_perm).reshape((- 1))
return LDFactor(f.model, f.var_idx, Prob(prob)) | -7,319,385,636,117,433,000 | Converts inferlo.DiscreteFactor to LDFactor. | inferlo/generic/libdai_bp.py | from_inferlo_factor | InferLO/inferlo | python | @staticmethod
def from_inferlo_factor(f: DiscreteFactor):
rev_perm = list(range(len(f.var_idx)))[::(- 1)]
prob = f.values.transpose(rev_perm).reshape((- 1))
return LDFactor(f.model, f.var_idx, Prob(prob)) |
def to_inferlo_factor(self) -> DiscreteFactor:
'Converts LDFactor to inferlo.DiscreteFactor.'
sizes = [self.model.get_variable(i).domain.size() for i in self.var_idx[::(- 1)]]
libdai_tensor = self.p.p.reshape(sizes)
rev_perm = list(range(len(self.var_idx)))[::(- 1)]
inferlo_tensor = libdai_tensor.tr... | -7,055,429,566,873,699,000 | Converts LDFactor to inferlo.DiscreteFactor. | inferlo/generic/libdai_bp.py | to_inferlo_factor | InferLO/inferlo | python | def to_inferlo_factor(self) -> DiscreteFactor:
sizes = [self.model.get_variable(i).domain.size() for i in self.var_idx[::(- 1)]]
libdai_tensor = self.p.p.reshape(sizes)
rev_perm = list(range(len(self.var_idx)))[::(- 1)]
inferlo_tensor = libdai_tensor.transpose(rev_perm)
return DiscreteFactor(se... |
def combine_with_factor(self, other: LDFactor, func: Callable[([float, float], float)]):
'Applies binary function to two factors.'
for i in other.var_idx:
assert (i in self.var_idx)
for idx in range(len(self.p.p)):
j = other._encode_value_index(self._decode_value_index(idx))
self.p.p... | -853,957,249,262,632,400 | Applies binary function to two factors. | inferlo/generic/libdai_bp.py | combine_with_factor | InferLO/inferlo | python | def combine_with_factor(self, other: LDFactor, func: Callable[([float, float], float)]):
for i in other.var_idx:
assert (i in self.var_idx)
for idx in range(len(self.p.p)):
j = other._encode_value_index(self._decode_value_index(idx))
self.p.p[idx] = func(self.p.p[idx], other.p.p[j])... |
def marginal(self, new_var_idx, normed=True) -> LDFactor:
'Sums factor over some variables.'
result = self.to_inferlo_factor().marginal(new_var_idx)
result = LDFactor.from_inferlo_factor(result)
if normed:
result.p.normalize()
return result | -300,902,764,208,707,500 | Sums factor over some variables. | inferlo/generic/libdai_bp.py | marginal | InferLO/inferlo | python | def marginal(self, new_var_idx, normed=True) -> LDFactor:
result = self.to_inferlo_factor().marginal(new_var_idx)
result = LDFactor.from_inferlo_factor(result)
if normed:
result.p.normalize()
return result |
def max_marginal(self, new_var_idx, normed=True) -> LDFactor:
'Eleiminates certain variables by finding maximum.'
result = self.to_inferlo_factor().max_marginal(new_var_idx)
result = LDFactor.from_inferlo_factor(result)
if normed:
result.p.normalize()
return result | 1,158,098,587,500,319,000 | Eleiminates certain variables by finding maximum. | inferlo/generic/libdai_bp.py | max_marginal | InferLO/inferlo | python | def max_marginal(self, new_var_idx, normed=True) -> LDFactor:
result = self.to_inferlo_factor().max_marginal(new_var_idx)
result = LDFactor.from_inferlo_factor(result)
if normed:
result.p.normalize()
return result |
def clone(self):
'Makes a copy of this factor.'
return LDFactor(self.model, self.var_idx, self.p.clone()) | -1,412,512,557,047,017,000 | Makes a copy of this factor. | inferlo/generic/libdai_bp.py | clone | InferLO/inferlo | python | def clone(self):
return LDFactor(self.model, self.var_idx, self.p.clone()) |
def _decode_value_index(self, idx):
'Returns dict from variable id to variable value.'
ans = dict()
for var_id in self.var_idx:
size = self.model.get_variable(var_id).domain.size()
ans[var_id] = (idx % size)
idx //= size
return ans | -4,562,561,243,723,303,400 | Returns dict from variable id to variable value. | inferlo/generic/libdai_bp.py | _decode_value_index | InferLO/inferlo | python | def _decode_value_index(self, idx):
ans = dict()
for var_id in self.var_idx:
size = self.model.get_variable(var_id).domain.size()
ans[var_id] = (idx % size)
idx //= size
return ans |
@staticmethod
def infer(model, options=None):
'Runs inference BP algorithm for given model.\n\n Supports all options which libdai::BP supports. Refer to libDAI\n documentation for options descritpion.\n '
if (options is None):
options = {'tol': 1e-09, 'logdomain': 0, 'updates': 'SEQ... | -3,472,154,361,382,406,700 | Runs inference BP algorithm for given model.
Supports all options which libdai::BP supports. Refer to libDAI
documentation for options descritpion. | inferlo/generic/libdai_bp.py | infer | InferLO/inferlo | python | @staticmethod
def infer(model, options=None):
'Runs inference BP algorithm for given model.\n\n Supports all options which libdai::BP supports. Refer to libDAI\n documentation for options descritpion.\n '
if (options is None):
options = {'tol': 1e-09, 'logdomain': 0, 'updates': 'SEQ... |
def _construct(self):
'Helper function for constructors.'
self._edges = []
for i in range(self.nrVars):
self._edges.append([])
for _ in self.nbV[i]:
size = self._var_size(i)
new_ep = EdgeProp(index=None, message=Prob.uniform(size), new_message=Prob.uniform(size), resi... | 5,862,436,295,012,486,000 | Helper function for constructors. | inferlo/generic/libdai_bp.py | _construct | InferLO/inferlo | python | def _construct(self):
self._edges = []
for i in range(self.nrVars):
self._edges.append([])
for _ in self.nbV[i]:
size = self._var_size(i)
new_ep = EdgeProp(index=None, message=Prob.uniform(size), new_message=Prob.uniform(size), residual=0.0)
self._edges[i... |
def init(self):
'Initializes messages awith default values.'
c = (0.0 if self.logdomain else 1.0)
for i in range(self.nrVars):
for ii in self.nbV[i]:
self._edges[i][ii.iter].message.fill(c)
self._edges[i][ii.iter].new_message.fill(c)
if (self.updates == 'SEQMAX'):... | 4,076,126,271,826,050,600 | Initializes messages awith default values. | inferlo/generic/libdai_bp.py | init | InferLO/inferlo | python | def init(self):
c = (0.0 if self.logdomain else 1.0)
for i in range(self.nrVars):
for ii in self.nbV[i]:
self._edges[i][ii.iter].message.fill(c)
self._edges[i][ii.iter].new_message.fill(c)
if (self.updates == 'SEQMAX'):
self._update_residual(i, ii... |
def find_max_residual(self):
'Find max residual.'
max_r = (- np.inf)
best_edge = None
for i in range(self.nrVars):
for _I in range(len(self.nbV[i])):
if (self._edges[i][_I].residual > max_r):
max_r = self._edges[i][_I].residual
best_edge = (i, _I)
... | -6,233,666,094,231,453,000 | Find max residual. | inferlo/generic/libdai_bp.py | find_max_residual | InferLO/inferlo | python | def find_max_residual(self):
max_r = (- np.inf)
best_edge = None
for i in range(self.nrVars):
for _I in range(len(self.nbV[i])):
if (self._edges[i][_I].residual > max_r):
max_r = self._edges[i][_I].residual
best_edge = (i, _I)
return best_edge |
def _calc_incoming_message_product(self, ii: int, without_i: bool, i: int) -> Prob:
'Calculate the product of factor \x07 I and the incoming messages.\n\n If without_i == True, the message coming from variable i is omitted\n from the product.\n\n This function is used by calc_new_message and ca... | -888,266,374,908,817,400 | Calculate the product of factor I and the incoming messages.
If without_i == True, the message coming from variable i is omitted
from the product.
This function is used by calc_new_message and calc_belief_f. | inferlo/generic/libdai_bp.py | _calc_incoming_message_product | InferLO/inferlo | python | def _calc_incoming_message_product(self, ii: int, without_i: bool, i: int) -> Prob:
'Calculate the product of factor \x07 I and the incoming messages.\n\n If without_i == True, the message coming from variable i is omitted\n from the product.\n\n This function is used by calc_new_message and ca... |
def run(self):
'Runs BP algorithm.'
tic = time.time()
max_diff = np.inf
while ((self._iters < self.maxiter) and (max_diff > self.tol) and ((time.time() - tic) < self.maxtime)):
if (self.updates == 'SEQMAX'):
if (self._iters == 0):
for i in range(self.nrVars):
... | -772,364,498,801,806,700 | Runs BP algorithm. | inferlo/generic/libdai_bp.py | run | InferLO/inferlo | python | def run(self):
tic = time.time()
max_diff = np.inf
while ((self._iters < self.maxiter) and (max_diff > self.tol) and ((time.time() - tic) < self.maxtime)):
if (self.updates == 'SEQMAX'):
if (self._iters == 0):
for i in range(self.nrVars):
for ii i... |
def log_z(self) -> float:
'Calculates logarithm of the partition function.'
ans = 0.0
for i in range(self.nrVars):
ans += ((1.0 - len(self.nbV[i])) * self._belief_v(i).p.entropy())
for ii in range(self.nrFactors):
ans -= dist_kl(self._belief_f(ii).p, self.factors[ii].p)
return ans | -1,830,153,131,984,670,200 | Calculates logarithm of the partition function. | inferlo/generic/libdai_bp.py | log_z | InferLO/inferlo | python | def log_z(self) -> float:
ans = 0.0
for i in range(self.nrVars):
ans += ((1.0 - len(self.nbV[i])) * self._belief_v(i).p.entropy())
for ii in range(self.nrFactors):
ans -= dist_kl(self._belief_f(ii).p, self.factors[ii].p)
return ans |
def marg_prob(self) -> np.ndarray:
'Calculates marginal probabilities.'
max_domain_size = np.max([self._var_size(i) for i in range(self.nrVars)])
ans = np.zeros((self.nrVars, max_domain_size), dtype=np.float64)
for var_id in range(self.nrVars):
ans[var_id, 0:self._var_size(var_id)] = self._belie... | 4,195,681,131,789,335,000 | Calculates marginal probabilities. | inferlo/generic/libdai_bp.py | marg_prob | InferLO/inferlo | python | def marg_prob(self) -> np.ndarray:
max_domain_size = np.max([self._var_size(i) for i in range(self.nrVars)])
ans = np.zeros((self.nrVars, max_domain_size), dtype=np.float64)
for var_id in range(self.nrVars):
ans[var_id, 0:self._var_size(var_id)] = self._belief_v(var_id).p.p
return ans |
def __init__(self, storage, move_scheme=None, sample_set=None, initialize=True):
'\n Parameters\n ----------\n storage : :class:`openpathsampling.storage.Storage`\n the storage where all results should be stored in\n move_scheme : :class:`openpathsampling.MoveScheme`\n ... | 8,646,892,375,445,471,000 | Parameters
----------
storage : :class:`openpathsampling.storage.Storage`
the storage where all results should be stored in
move_scheme : :class:`openpathsampling.MoveScheme`
the move scheme used for the pathsampling cycle
sample_set : :class:`openpathsampling.SampleSet`
the initial SampleSet for the Simula... | openpathsampling/pathsimulators/path_sampling.py | __init__ | bolhuis/openpathsampling | python | def __init__(self, storage, move_scheme=None, sample_set=None, initialize=True):
'\n Parameters\n ----------\n storage : :class:`openpathsampling.storage.Storage`\n the storage where all results should be stored in\n move_scheme : :class:`openpathsampling.MoveScheme`\n ... |
def save_current_step(self):
'\n Save the current step to the storage\n\n '
if ((self.storage is not None) and (self._current_step is not None)):
try:
self.storage.stash(self._current_step)
except AttributeError:
self.storage.steps.save(self._current_step) | -6,005,775,065,783,409,000 | Save the current step to the storage | openpathsampling/pathsimulators/path_sampling.py | save_current_step | bolhuis/openpathsampling | python | def save_current_step(self):
'\n \n\n '
if ((self.storage is not None) and (self._current_step is not None)):
try:
self.storage.stash(self._current_step)
except AttributeError:
self.storage.steps.save(self._current_step) |
@classmethod
def from_step(cls, storage, step, initialize=True):
'\n\n Parameters\n ----------\n storage : :class:`openpathsampling.storage.Storage`\n the storage to be used to hold the simulation results\n step : :class:`openpathsampling.MCStep`\n the step used to ... | 4,474,719,290,868,421,600 | Parameters
----------
storage : :class:`openpathsampling.storage.Storage`
the storage to be used to hold the simulation results
step : :class:`openpathsampling.MCStep`
the step used to fill the initial parameters
initialize : bool
if `False` the new PathSimulator will continue at the given step and
not ... | openpathsampling/pathsimulators/path_sampling.py | from_step | bolhuis/openpathsampling | python | @classmethod
def from_step(cls, storage, step, initialize=True):
'\n\n Parameters\n ----------\n storage : :class:`openpathsampling.storage.Storage`\n the storage to be used to hold the simulation results\n step : :class:`openpathsampling.MCStep`\n the step used to ... |
def restart_at_step(self, step, storage=None):
'\n Continue with a loaded pathsampling at a given step\n\n Notes\n -----\n You can only continue from a step that is compatible in the sense\n that it was previously generated from the pathsampling instance.\n\n If you want to... | -583,609,655,033,610,800 | Continue with a loaded pathsampling at a given step
Notes
-----
You can only continue from a step that is compatible in the sense
that it was previously generated from the pathsampling instance.
If you want to switch the move scheme you need to create a new
pathsampling instance. You can do so with the constructor or... | openpathsampling/pathsimulators/path_sampling.py | restart_at_step | bolhuis/openpathsampling | python | def restart_at_step(self, step, storage=None):
'\n Continue with a loaded pathsampling at a given step\n\n Notes\n -----\n You can only continue from a step that is compatible in the sense\n that it was previously generated from the pathsampling instance.\n\n If you want to... |
def run_until_decorrelated(self, time_reversal=True):
'Run until all trajectories are decorrelated.\n\n This runs until all the replicas in ``self.sample_set`` have\n decorrelated from their initial conditions. "Decorrelated" here is\n meant in the sense commonly used in one-way shooting: this ... | 5,267,402,370,953,656,000 | Run until all trajectories are decorrelated.
This runs until all the replicas in ``self.sample_set`` have
decorrelated from their initial conditions. "Decorrelated" here is
meant in the sense commonly used in one-way shooting: this runs
until no configurations from the original trajectories remain. | openpathsampling/pathsimulators/path_sampling.py | run_until_decorrelated | bolhuis/openpathsampling | python | def run_until_decorrelated(self, time_reversal=True):
'Run until all trajectories are decorrelated.\n\n This runs until all the replicas in ``self.sample_set`` have\n decorrelated from their initial conditions. "Decorrelated" here is\n meant in the sense commonly used in one-way shooting: this ... |
def create_user(self, email, password=None, **extra_fields):
'\n Creates and saves a User with the given email and\n password.\n '
now = timezone.now()
if (not email):
raise ValueError('The given email must be set')
email = UserManager.normalize_email(email)
user = self.... | -6,193,041,823,426,439,000 | Creates and saves a User with the given email and
password. | src/oscar/apps/customer/abstract_models.py | create_user | Abirami15/django-oscar | python | def create_user(self, email, password=None, **extra_fields):
'\n Creates and saves a User with the given email and\n password.\n '
now = timezone.now()
if (not email):
raise ValueError('The given email must be set')
email = UserManager.normalize_email(email)
user = self.... |
def get_full_name(self):
'\n Return the first_name plus the last_name, with a space in between.\n '
full_name = ('%s %s' % (self.first_name, self.last_name))
return full_name.strip() | 102,124,964,758,521,170 | Return the first_name plus the last_name, with a space in between. | src/oscar/apps/customer/abstract_models.py | get_full_name | Abirami15/django-oscar | python | def get_full_name(self):
'\n \n '
full_name = ('%s %s' % (self.first_name, self.last_name))
return full_name.strip() |
def get_short_name(self):
'\n Return the short name for the user.\n '
return self.first_name | -62,519,838,540,969,440 | Return the short name for the user. | src/oscar/apps/customer/abstract_models.py | get_short_name | Abirami15/django-oscar | python | def get_short_name(self):
'\n \n '
return self.first_name |
def email_user(self, subject, message, from_email=None, **kwargs):
'\n Send an email to this user.\n '
send_mail(subject, message, from_email, [self.email], **kwargs) | -3,977,850,786,468,333,600 | Send an email to this user. | src/oscar/apps/customer/abstract_models.py | email_user | Abirami15/django-oscar | python | def email_user(self, subject, message, from_email=None, **kwargs):
'\n \n '
send_mail(subject, message, from_email, [self.email], **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.