hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | enable_proxy | <not_specific> | async def enable_proxy(self):
"""Enables a proxy server.
Requests are proxied through US Proxies to prevent MailChimp
blocks. This is an accepted technique among integrators and
does not violate MailChimp's Terms of Service.
"""
# Don't use a proxy if environmen... | Enables a proxy server.
Requests are proxied through US Proxies to prevent MailChimp
blocks. This is an accepted technique among integrators and
does not violate MailChimp's Terms of Service.
| Enables a proxy server.
Requests are proxied through US Proxies to prevent MailChimp
blocks. This is an accepted technique among integrators and
does not violate MailChimp's Terms of Service. | [
"Enables",
"a",
"proxy",
"server",
".",
"Requests",
"are",
"proxied",
"through",
"US",
"Proxies",
"to",
"prevent",
"MailChimp",
"blocks",
".",
"This",
"is",
"an",
"accepted",
"technique",
"among",
"integrators",
"and",
"does",
"not",
"violate",
"MailChimp",
"'... | async def enable_proxy(self):
if os.environ.get('NO_PROXY'):
self.logger.info(
'NO_PROXY environment variable set. Not using a proxy.')
return
process = current_process()
try:
proxy_process_number = str(process.index + 1)
except Attribu... | [
"async",
"def",
"enable_proxy",
"(",
"self",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'NO_PROXY'",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'NO_PROXY environment variable set. Not using a proxy.'",
")",
"return",
"process",
"=",
"curr... | Enables a proxy server. | [
"Enables",
"a",
"proxy",
"server",
"."
] | [
"\"\"\"Enables a proxy server.\r\n\r\n Requests are proxied through US Proxies to prevent MailChimp\r\n blocks. This is an accepted technique among integrators and\r\n does not violate MailChimp's Terms of Service.\r\n \"\"\"",
"# Don't use a proxy if environment variable is set, e.g. ... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | make_async_request | <not_specific> | async def make_async_request(self, url, params, session, retry=0):
"""Makes an async request using aiohttp.
Makes a get request.
If successful, returns the response text future.
If the request times out, or returns a status code
that we want to retry, recursively retry the... | Makes an async request using aiohttp.
Makes a get request.
If successful, returns the response text future.
If the request times out, or returns a status code
that we want to retry, recursively retry the request
up to MAX_RETRIES times using exponential backoff.
... | Makes an async request using aiohttp.
Makes a get request.
If successful, returns the response text future.
If the request times out, or returns a status code
that we want to retry, recursively retry the request
up to MAX_RETRIES times using exponential backoff. | [
"Makes",
"an",
"async",
"request",
"using",
"aiohttp",
".",
"Makes",
"a",
"get",
"request",
".",
"If",
"successful",
"returns",
"the",
"response",
"text",
"future",
".",
"If",
"the",
"request",
"times",
"out",
"or",
"returns",
"a",
"status",
"code",
"that"... | async def make_async_request(self, url, params, session, retry=0):
try:
async with session.get(url, params=params,
auth=BasicAuth('shorenstein',
self.api_key),
proxy=self.proxy) as... | [
"async",
"def",
"make_async_request",
"(",
"self",
",",
"url",
",",
"params",
",",
"session",
",",
"retry",
"=",
"0",
")",
":",
"try",
":",
"async",
"with",
"session",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
",",
"auth",
"=",
"BasicAuth... | Makes an async request using aiohttp. | [
"Makes",
"an",
"async",
"request",
"using",
"aiohttp",
"."
] | [
"\"\"\"Makes an async request using aiohttp.\r\n\r\n Makes a get request.\r\n If successful, returns the response text future.\r\n If the request times out, or returns a status code\r\n that we want to retry, recursively retry the request\r\n up to MAX_RETRIES times using exponent... | [
{
"param": "self",
"type": null
},
{
"param": "url",
"type": null
},
{
"param": "params",
"type": null
},
{
"param": "session",
"type": null
},
{
"param": "retry",
"type": null
}
] | {
"returns": [
{
"docstring": "An asyncio future, which, when awaited,\ncontains the request response.",
"docstring_tokens": [
"An",
"asyncio",
"future",
"which",
"when",
"awaited",
"contains",
"the",
"request",
"response"... |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | make_async_requests | <not_specific> | async def make_async_requests(self, sem, url, params, session):
"""Makes a number of async requests using a semaphore.
Args:
sem: A semaphore to limit the number of concurrent async
requests.
url: See make_async_request().
params: See make_asyn... | Makes a number of async requests using a semaphore.
Args:
sem: A semaphore to limit the number of concurrent async
requests.
url: See make_async_request().
params: See make_async_request().
session: See make_async_request().
Retu... | Makes a number of async requests using a semaphore. | [
"Makes",
"a",
"number",
"of",
"async",
"requests",
"using",
"a",
"semaphore",
"."
] | async def make_async_requests(self, sem, url, params, session):
async with sem:
res = await self.make_async_request(url, params, session)
return json.loads(res) | [
"async",
"def",
"make_async_requests",
"(",
"self",
",",
"sem",
",",
"url",
",",
"params",
",",
"session",
")",
":",
"async",
"with",
"sem",
":",
"res",
"=",
"await",
"self",
".",
"make_async_request",
"(",
"url",
",",
"params",
",",
"session",
")",
"r... | Makes a number of async requests using a semaphore. | [
"Makes",
"a",
"number",
"of",
"async",
"requests",
"using",
"a",
"semaphore",
"."
] | [
"\"\"\"Makes a number of async requests using a semaphore.\r\n\r\n Args:\r\n sem: A semaphore to limit the number of concurrent async\r\n requests.\r\n url: See make_async_request().\r\n params: See make_async_request().\r\n session: See make_async_r... | [
{
"param": "self",
"type": null
},
{
"param": "sem",
"type": null
},
{
"param": "url",
"type": null
},
{
"param": "params",
"type": null
},
{
"param": "session",
"type": null
}
] | {
"returns": [
{
"docstring": "An asyncio future resolved into a dictionary containing\nrequest results.",
"docstring_tokens": [
"An",
"asyncio",
"future",
"resolved",
"into",
"a",
"dictionary",
"containing",
"request",
"r... |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | import_list_members | null | async def import_list_members(self):
"""Requests basic information about MailChimp list members in chunks.
This includes the member status, member stats, etc.
Requests are made asynchronously (up to CHUNK_SIZE members
per requests) using aiohttp. This speeds up the process
... | Requests basic information about MailChimp list members in chunks.
This includes the member status, member stats, etc.
Requests are made asynchronously (up to CHUNK_SIZE members
per requests) using aiohttp. This speeds up the process
significantly and prevents timeouts.
Af... | Requests basic information about MailChimp list members in chunks.
This includes the member status, member stats, etc.
Requests are made asynchronously (up to CHUNK_SIZE members
per requests) using aiohttp. This speeds up the process
significantly and prevents timeouts.
After the requests have completed, parses the res... | [
"Requests",
"basic",
"information",
"about",
"MailChimp",
"list",
"members",
"in",
"chunks",
".",
"This",
"includes",
"the",
"member",
"status",
"member",
"stats",
"etc",
".",
"Requests",
"are",
"made",
"asynchronously",
"(",
"up",
"to",
"CHUNK_SIZE",
"members",... | async def import_list_members(self):
await self.enable_proxy()
request_uri = ('https://{}.api.mailchimp.com/3.0/lists/{}/'
'members'.format(self.data_center, self.id))
tasks = []
responses = None
sem = asyncio.Semaphore(self.MAX_CONNECTIONS)
number_... | [
"async",
"def",
"import_list_members",
"(",
"self",
")",
":",
"await",
"self",
".",
"enable_proxy",
"(",
")",
"request_uri",
"=",
"(",
"'https://{}.api.mailchimp.com/3.0/lists/{}/'",
"'members'",
".",
"format",
"(",
"self",
".",
"data_center",
",",
"self",
".",
... | Requests basic information about MailChimp list members in chunks. | [
"Requests",
"basic",
"information",
"about",
"MailChimp",
"list",
"members",
"in",
"chunks",
"."
] | [
"\"\"\"Requests basic information about MailChimp list members in chunks.\r\n\r\n This includes the member status, member stats, etc.\r\n Requests are made asynchronously (up to CHUNK_SIZE members\r\n per requests) using aiohttp. This speeds up the process\r\n significantly and prevents ... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | import_sub_activity | null | async def import_sub_activity(self): # pylint: disable=too-many-locals
"""Requests each subscriber's recent activity.
First, gets a list of subscribers.
Then makes the requests one-by-one using aiohttp (MailChimp's API is
very inefficient and you cannot request multiple subscribers... | Requests each subscriber's recent activity.
First, gets a list of subscribers.
Then makes the requests one-by-one using aiohttp (MailChimp's API is
very inefficient and you cannot request multiple subscribers' activity
at the same time).
After the requests have completed, ... | Requests each subscriber's recent activity.
First, gets a list of subscribers.
Then makes the requests one-by-one using aiohttp (MailChimp's API is
very inefficient and you cannot request multiple subscribers' activity
at the same time).
After the requests have completed, parses the results, turns them into
a pandas da... | [
"Requests",
"each",
"subscriber",
"'",
"s",
"recent",
"activity",
".",
"First",
"gets",
"a",
"list",
"of",
"subscribers",
".",
"Then",
"makes",
"the",
"requests",
"one",
"-",
"by",
"-",
"one",
"using",
"aiohttp",
"(",
"MailChimp",
"'",
"s",
"API",
"is",
... | async def import_sub_activity(self):
params = (
('fields', 'activity.action,activity.timestamp,email_id'),
('exclude_fields', 'total_items,_links')
)
request_uri = ('https://{}.api.mailchimp.com/3.0/lists/{}/members/'
'{}/activity'.format(self.data... | [
"async",
"def",
"import_sub_activity",
"(",
"self",
")",
":",
"params",
"=",
"(",
"(",
"'fields'",
",",
"'activity.action,activity.timestamp,email_id'",
")",
",",
"(",
"'exclude_fields'",
",",
"'total_items,_links'",
")",
")",
"request_uri",
"=",
"(",
"'https://{}.a... | Requests each subscriber's recent activity. | [
"Requests",
"each",
"subscriber",
"'",
"s",
"recent",
"activity",
"."
] | [
"# pylint: disable=too-many-locals\r",
"\"\"\"Requests each subscriber's recent activity.\r\n\r\n First, gets a list of subscribers.\r\n Then makes the requests one-by-one using aiohttp (MailChimp's API is\r\n very inefficient and you cannot request multiple subscribers' activity\r\n a... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | flatten | null | def flatten(self):
"""Removes nested jsons from the dataframe."""
# Extract member stats from nested json
# Then store them in a flattened dataframe
stats = json_normalize(self.df['stats'].tolist())
# Merge the dataframes
self.df = (self.df[['status', 'timestamp... | Removes nested jsons from the dataframe. | Removes nested jsons from the dataframe. | [
"Removes",
"nested",
"jsons",
"from",
"the",
"dataframe",
"."
] | def flatten(self):
stats = json_normalize(self.df['stats'].tolist())
self.df = (self.df[['status', 'timestamp_opt', 'timestamp_signup',
'id', 'recent_open']].join(stats)) | [
"def",
"flatten",
"(",
"self",
")",
":",
"stats",
"=",
"json_normalize",
"(",
"self",
".",
"df",
"[",
"'stats'",
"]",
".",
"tolist",
"(",
")",
")",
"self",
".",
"df",
"=",
"(",
"self",
".",
"df",
"[",
"[",
"'status'",
",",
"'timestamp_opt'",
",",
... | Removes nested jsons from the dataframe. | [
"Removes",
"nested",
"jsons",
"from",
"the",
"dataframe",
"."
] | [
"\"\"\"Removes nested jsons from the dataframe.\"\"\"",
"# Extract member stats from nested json\r",
"# Then store them in a flattened dataframe\r",
"# Merge the dataframes\r"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | calc_frequency | null | def calc_frequency(self, date_created, campaign_count):
"""Calculates the average number of days per campaign sent. Automatically
zero if fewer than 10 campaigns have been sent total."""
campaign_count = int(campaign_count)
if campaign_count < 10:
self.frequency = 0
... | Calculates the average number of days per campaign sent. Automatically
zero if fewer than 10 campaigns have been sent total. | Calculates the average number of days per campaign sent. Automatically
zero if fewer than 10 campaigns have been sent total. | [
"Calculates",
"the",
"average",
"number",
"of",
"days",
"per",
"campaign",
"sent",
".",
"Automatically",
"zero",
"if",
"fewer",
"than",
"10",
"campaigns",
"have",
"been",
"sent",
"total",
"."
] | def calc_frequency(self, date_created, campaign_count):
campaign_count = int(campaign_count)
if campaign_count < 10:
self.frequency = 0
else:
now = datetime.now(timezone.utc)
created = (iso8601.parse_date(date_created)
if isinstance(date... | [
"def",
"calc_frequency",
"(",
"self",
",",
"date_created",
",",
"campaign_count",
")",
":",
"campaign_count",
"=",
"int",
"(",
"campaign_count",
")",
"if",
"campaign_count",
"<",
"10",
":",
"self",
".",
"frequency",
"=",
"0",
"else",
":",
"now",
"=",
"date... | Calculates the average number of days per campaign sent. | [
"Calculates",
"the",
"average",
"number",
"of",
"days",
"per",
"campaign",
"sent",
"."
] | [
"\"\"\"Calculates the average number of days per campaign sent. Automatically\r\n zero if fewer than 10 campaigns have been sent total.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "date_created",
"type": null
},
{
"param": "campaign_count",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "date_created",
"type": null,
"docstring": null,
"docstring_to... |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | calc_histogram | null | def calc_histogram(self):
"""Calculates the distribution for subscriber open rate."""
bin_boundaries = np.linspace(0, 1, num=11)
bins = (pd.cut(
self.df.loc[self.df['status'] == 'subscribed', 'avg_open_rate'],
bin_boundaries, include_lowest=True))
self.hist_... | Calculates the distribution for subscriber open rate. | Calculates the distribution for subscriber open rate. | [
"Calculates",
"the",
"distribution",
"for",
"subscriber",
"open",
"rate",
"."
] | def calc_histogram(self):
bin_boundaries = np.linspace(0, 1, num=11)
bins = (pd.cut(
self.df.loc[self.df['status'] == 'subscribed', 'avg_open_rate'],
bin_boundaries, include_lowest=True))
self.hist_bin_counts = (pd.value_counts(bins, sort=False).tolist()) | [
"def",
"calc_histogram",
"(",
"self",
")",
":",
"bin_boundaries",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"num",
"=",
"11",
")",
"bins",
"=",
"(",
"pd",
".",
"cut",
"(",
"self",
".",
"df",
".",
"loc",
"[",
"self",
".",
"df",
"[",
... | Calculates the distribution for subscriber open rate. | [
"Calculates",
"the",
"distribution",
"for",
"subscriber",
"open",
"rate",
"."
] | [
"\"\"\"Calculates the distribution for subscriber open rate.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | calc_high_open_rate_pct | null | def calc_high_open_rate_pct(self):
"""Calcuates the percentage of subscribers who open >80% of emails."""
# Sum the number of rows where average open rate exceeds 0.8
# And the member is a subscriber
# Then divide by the total number of rows
self.high_open_rt_pct = (
... | Calcuates the percentage of subscribers who open >80% of emails. | Calcuates the percentage of subscribers who open >80% of emails. | [
"Calcuates",
"the",
"percentage",
"of",
"subscribers",
"who",
"open",
">",
"80%",
"of",
"emails",
"."
] | def calc_high_open_rate_pct(self):
self.high_open_rt_pct = (
sum(x > 0.8 for x in self.df[self.df['status'] == 'subscribed']
['avg_open_rate']) / self.subscribers) | [
"def",
"calc_high_open_rate_pct",
"(",
"self",
")",
":",
"self",
".",
"high_open_rt_pct",
"=",
"(",
"sum",
"(",
"x",
">",
"0.8",
"for",
"x",
"in",
"self",
".",
"df",
"[",
"self",
".",
"df",
"[",
"'status'",
"]",
"==",
"'subscribed'",
"]",
"[",
"'avg_... | Calcuates the percentage of subscribers who open >80% of emails. | [
"Calcuates",
"the",
"percentage",
"of",
"subscribers",
"who",
"open",
">",
"80%",
"of",
"emails",
"."
] | [
"\"\"\"Calcuates the percentage of subscribers who open >80% of emails.\"\"\"",
"# Sum the number of rows where average open rate exceeds 0.8\r",
"# And the member is a subscriber\r",
"# Then divide by the total number of rows\r"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6beadea7f8be74d24e6acec459a6a77996abfe55 | ShorensteinCenter/Benchmarks-Program | app/lists.py | [
"MIT"
] | Python | calc_cur_yr_stats | null | def calc_cur_yr_stats(self):
"""Calculates metrics related to activity
that occured in the previous year."""
# Total number of subsribers without an open within the last year
cur_yr_inactive_subs = (self.subscribers -
int(self.df['recent_open'].coun... | Calculates metrics related to activity
that occured in the previous year. | Calculates metrics related to activity
that occured in the previous year. | [
"Calculates",
"metrics",
"related",
"to",
"activity",
"that",
"occured",
"in",
"the",
"previous",
"year",
"."
] | def calc_cur_yr_stats(self):
cur_yr_inactive_subs = (self.subscribers -
int(self.df['recent_open'].count()))
self.cur_yr_inactive_pct = cur_yr_inactive_subs / self.subscribers | [
"def",
"calc_cur_yr_stats",
"(",
"self",
")",
":",
"cur_yr_inactive_subs",
"=",
"(",
"self",
".",
"subscribers",
"-",
"int",
"(",
"self",
".",
"df",
"[",
"'recent_open'",
"]",
".",
"count",
"(",
")",
")",
")",
"self",
".",
"cur_yr_inactive_pct",
"=",
"cu... | Calculates metrics related to activity
that occured in the previous year. | [
"Calculates",
"metrics",
"related",
"to",
"activity",
"that",
"occured",
"in",
"the",
"previous",
"year",
"."
] | [
"\"\"\"Calculates metrics related to activity\r\n that occured in the previous year.\"\"\"",
"# Total number of subsribers without an open within the last year\r",
"# Percent of such subscribers\r"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | add | null | def add(self, node, key=None):
""" Add a node object to the collection. If no key is specified,
the next available numeric key is used instead
Args:
node: Vizard node3d object """
if key is None:
# Find a free numerical key
key = self._next_idx
... | Add a node object to the collection. If no key is specified,
the next available numeric key is used instead
Args:
node: Vizard node3d object | Add a node object to the collection. If no key is specified,
the next available numeric key is used instead | [
"Add",
"a",
"node",
"object",
"to",
"the",
"collection",
".",
"If",
"no",
"key",
"is",
"specified",
"the",
"next",
"available",
"numeric",
"key",
"is",
"used",
"instead"
] | def add(self, node, key=None):
if key is None:
key = self._next_idx
while key in self._o.keys():
key += 1
self._next_idx = key + 1
self[key] = node | [
"def",
"add",
"(",
"self",
",",
"node",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"self",
".",
"_next_idx",
"while",
"key",
"in",
"self",
".",
"_o",
".",
"keys",
"(",
")",
":",
"key",
"+=",
"1",
"self",
".... | Add a node object to the collection. | [
"Add",
"a",
"node",
"object",
"to",
"the",
"collection",
"."
] | [
"\"\"\" Add a node object to the collection. If no key is specified, \n the next available numeric key is used instead\n\n Args:\n node: Vizard node3d object \"\"\"",
"# Find a free numerical key"
] | [
{
"param": "self",
"type": null
},
{
"param": "node",
"type": null
},
{
"param": "key",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "node",
"type": null,
"docstring": "Vizard node3d object",
"do... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | show | null | def show(self, key, position=None, euler=None, scale=None, color=None):
""" Set a specific object from the collection to visible. Allows
quickly setting position, scale, euler orientation and/or color
in the same call.
Args:
key (str): Key of the object to show
... | Set a specific object from the collection to visible. Allows
quickly setting position, scale, euler orientation and/or color
in the same call.
Args:
key (str): Key of the object to show
position, euler, scale, color: optional inputs to Vizard
"set<X>" f... | Set a specific object from the collection to visible. Allows
quickly setting position, scale, euler orientation and/or color
in the same call. | [
"Set",
"a",
"specific",
"object",
"from",
"the",
"collection",
"to",
"visible",
".",
"Allows",
"quickly",
"setting",
"position",
"scale",
"euler",
"orientation",
"and",
"/",
"or",
"color",
"in",
"the",
"same",
"call",
"."
] | def show(self, key, position=None, euler=None, scale=None, color=None):
if position is not None:
self._o[key].setPosition(position)
if scale is not None:
self._o[key].setScale(scale)
if euler is not None:
self._o[key].setEuler(euler)
if color is not No... | [
"def",
"show",
"(",
"self",
",",
"key",
",",
"position",
"=",
"None",
",",
"euler",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"if",
"position",
"is",
"not",
"None",
":",
"self",
".",
"_o",
"[",
"key",
"]",
"."... | Set a specific object from the collection to visible. | [
"Set",
"a",
"specific",
"object",
"from",
"the",
"collection",
"to",
"visible",
"."
] | [
"\"\"\" Set a specific object from the collection to visible. Allows \n quickly setting position, scale, euler orientation and/or color\n in the same call.\n\n Args:\n key (str): Key of the object to show\n position, euler, scale, color: optional inputs to Vizard\n ... | [
{
"param": "self",
"type": null
},
{
"param": "key",
"type": null
},
{
"param": "position",
"type": null
},
{
"param": "euler",
"type": null
},
{
"param": "scale",
"type": null
},
{
"param": "color",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "key",
"type": null,
"docstring": "Key of the object to show",
... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | showOnly | null | def showOnly(self, key, position=None, euler=None, scale=None, color=None):
""" Show only the specified object from the collection,
hiding all other objects. Allows quickly setting position,
scale, euler orientation and/or color in the same call.
Args:
key (str): Key of the... | Show only the specified object from the collection,
hiding all other objects. Allows quickly setting position,
scale, euler orientation and/or color in the same call.
Args:
key (str): Key of the object to show
position, euler, scale, color: optional inputs to Vizard
... | Show only the specified object from the collection,
hiding all other objects. Allows quickly setting position,
scale, euler orientation and/or color in the same call. | [
"Show",
"only",
"the",
"specified",
"object",
"from",
"the",
"collection",
"hiding",
"all",
"other",
"objects",
".",
"Allows",
"quickly",
"setting",
"position",
"scale",
"euler",
"orientation",
"and",
"/",
"or",
"color",
"in",
"the",
"same",
"call",
"."
] | def showOnly(self, key, position=None, euler=None, scale=None, color=None):
self.hideAll()
self.show(key, position=position, euler=euler, scale=scale, color=color) | [
"def",
"showOnly",
"(",
"self",
",",
"key",
",",
"position",
"=",
"None",
",",
"euler",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"self",
".",
"hideAll",
"(",
")",
"self",
".",
"show",
"(",
"key",
",",
"position... | Show only the specified object from the collection,
hiding all other objects. | [
"Show",
"only",
"the",
"specified",
"object",
"from",
"the",
"collection",
"hiding",
"all",
"other",
"objects",
"."
] | [
"\"\"\" Show only the specified object from the collection,\n hiding all other objects. Allows quickly setting position, \n scale, euler orientation and/or color in the same call.\n\n Args:\n key (str): Key of the object to show\n position, euler, scale, color: optional inputs... | [
{
"param": "self",
"type": null
},
{
"param": "key",
"type": null
},
{
"param": "position",
"type": null
},
{
"param": "euler",
"type": null
},
{
"param": "scale",
"type": null
},
{
"param": "color",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "key",
"type": null,
"docstring": "Key of the object to show",
... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | fromFiles | <not_specific> | def fromFiles(cls, files):
""" Create a new ObjectCollection by loading assets from
a folder or list of file names. File base names will be used
as keys in the collection.
Args:
files: path spec, e.g. 'objects/*.glb', or list of file names
"""
obj = {}
... | Create a new ObjectCollection by loading assets from
a folder or list of file names. File base names will be used
as keys in the collection.
Args:
files: path spec, e.g. 'objects/*.glb', or list of file names
| Create a new ObjectCollection by loading assets from
a folder or list of file names. File base names will be used
as keys in the collection. | [
"Create",
"a",
"new",
"ObjectCollection",
"by",
"loading",
"assets",
"from",
"a",
"folder",
"or",
"list",
"of",
"file",
"names",
".",
"File",
"base",
"names",
"will",
"be",
"used",
"as",
"keys",
"in",
"the",
"collection",
"."
] | def fromFiles(cls, files):
obj = {}
if type(files) == str:
for of in glob.glob(files):
key = os.path.splitext(os.path.split(of)[1])[0]
obj[key] = vizfx.addChild(of)
obj[key].visible(False)
else:
for of in files:
... | [
"def",
"fromFiles",
"(",
"cls",
",",
"files",
")",
":",
"obj",
"=",
"{",
"}",
"if",
"type",
"(",
"files",
")",
"==",
"str",
":",
"for",
"of",
"in",
"glob",
".",
"glob",
"(",
"files",
")",
":",
"key",
"=",
"os",
".",
"path",
".",
"splitext",
"... | Create a new ObjectCollection by loading assets from
a folder or list of file names. | [
"Create",
"a",
"new",
"ObjectCollection",
"by",
"loading",
"assets",
"from",
"a",
"folder",
"or",
"list",
"of",
"file",
"names",
"."
] | [
"\"\"\" Create a new ObjectCollection by loading assets from\n a folder or list of file names. File base names will be used\n as keys in the collection.\n\n Args:\n files: path spec, e.g. 'objects/*.glb', or list of file names\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "files",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "files",
"type": null,
"docstring": "path spec, e.g. 'objects.glb', o... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | steamVREasySetup | <not_specific> | def steamVREasySetup(link_models=True, mono_mirror=True):
""" Initializes a SteamVR HMD and controllers using default settings.
This is a convenience function which essentially does the same as the
SteamVR examples bundled with Vizard, but in a single function call.
Args:
link_models (bo... | Initializes a SteamVR HMD and controllers using default settings.
This is a convenience function which essentially does the same as the
SteamVR examples bundled with Vizard, but in a single function call.
Args:
link_models (bool): if True, show 3d models linked to the controllers
mo... | Initializes a SteamVR HMD and controllers using default settings.
This is a convenience function which essentially does the same as the
SteamVR examples bundled with Vizard, but in a single function call. | [
"Initializes",
"a",
"SteamVR",
"HMD",
"and",
"controllers",
"using",
"default",
"settings",
".",
"This",
"is",
"a",
"convenience",
"function",
"which",
"essentially",
"does",
"the",
"same",
"as",
"the",
"SteamVR",
"examples",
"bundled",
"with",
"Vizard",
"but",
... | def steamVREasySetup(link_models=True, mono_mirror=True):
try:
import steamvr
controllers = []
hmd = steamvr.HMD()
navNode = viz.addGroup()
link = viz.link(navNode, viz.MainView)
link.preMultLinkable(hmd.getSensor())
hmd.link = link
hmd.setMonoMirror(... | [
"def",
"steamVREasySetup",
"(",
"link_models",
"=",
"True",
",",
"mono_mirror",
"=",
"True",
")",
":",
"try",
":",
"import",
"steamvr",
"controllers",
"=",
"[",
"]",
"hmd",
"=",
"steamvr",
".",
"HMD",
"(",
")",
"navNode",
"=",
"viz",
".",
"addGroup",
"... | Initializes a SteamVR HMD and controllers using default settings. | [
"Initializes",
"a",
"SteamVR",
"HMD",
"and",
"controllers",
"using",
"default",
"settings",
"."
] | [
"\"\"\" Initializes a SteamVR HMD and controllers using default settings. \n \n This is a convenience function which essentially does the same as the\n SteamVR examples bundled with Vizard, but in a single function call. \n\n Args:\n link_models (bool): if True, show 3d models linked to the contr... | [
{
"param": "link_models",
"type": null
},
{
"param": "mono_mirror",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "link_models",
"type": null,
"docstring": "if True, show 3d models linked to the controllers",
"docstring_tokens": [
"if",
"True",
"show",
"3d",
"models",
"linked",
"to",
... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | showVRText | null | def showVRText(msg='Text', color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05, duration=3.0):
""" Display head-locked message in VR for specified duration.
Args:
msg (str): Message text
color: RBG 3-tuple of color values
distance (float): Z rendering distance from MainView
scal... | Display head-locked message in VR for specified duration.
Args:
msg (str): Message text
color: RBG 3-tuple of color values
distance (float): Z rendering distance from MainView
scale (float): Text node scaling factor
duration (float): Message display duration (seconds)
... | Display head-locked message in VR for specified duration. | [
"Display",
"head",
"-",
"locked",
"message",
"in",
"VR",
"for",
"specified",
"duration",
"."
] | def showVRText(msg='Text', color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05, duration=3.0):
text = addHeadLockedText(msg=msg,
color=color,
distance=distance,
scale=scale)
fadeout = vizact.fadeTo(0, time=0.7)
yield viztask.... | [
"def",
"showVRText",
"(",
"msg",
"=",
"'Text'",
",",
"color",
"=",
"[",
"1.0",
",",
"1.0",
",",
"1.0",
"]",
",",
"distance",
"=",
"2.0",
",",
"scale",
"=",
"0.05",
",",
"duration",
"=",
"3.0",
")",
":",
"text",
"=",
"addHeadLockedText",
"(",
"msg",... | Display head-locked message in VR for specified duration. | [
"Display",
"head",
"-",
"locked",
"message",
"in",
"VR",
"for",
"specified",
"duration",
"."
] | [
"\"\"\" Display head-locked message in VR for specified duration.\n \n Args:\n msg (str): Message text\n color: RBG 3-tuple of color values\n distance (float): Z rendering distance from MainView\n scale (float): Text node scaling factor\n duration (float): Message display du... | [
{
"param": "msg",
"type": null
},
{
"param": "color",
"type": null
},
{
"param": "distance",
"type": null
},
{
"param": "scale",
"type": null
},
{
"param": "duration",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "msg",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "color",
"type": null,
"docstring": "RBG 3-tup... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | waitVRText | null | def waitVRText(msg='Text', color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05, keys=' ', controller=None):
""" Display head-locked message in VR and wait for key press.
Args:
msg (str): Message text
color: RBG 3-tuple of color values
distance (float): Z rendering distance from MainView... | Display head-locked message in VR and wait for key press.
Args:
msg (str): Message text
color: RBG 3-tuple of color values
distance (float): Z rendering distance from MainView
scale (float): Text node scaling factor
keys (str): Key code(s) to dismiss message (see viztas... | Display head-locked message in VR and wait for key press. | [
"Display",
"head",
"-",
"locked",
"message",
"in",
"VR",
"and",
"wait",
"for",
"key",
"press",
"."
] | def waitVRText(msg='Text', color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05, keys=' ', controller=None):
text = addHeadLockedText(msg=msg,
color=color,
distance=distance,
scale=scale)
if controller is not None:
event =... | [
"def",
"waitVRText",
"(",
"msg",
"=",
"'Text'",
",",
"color",
"=",
"[",
"1.0",
",",
"1.0",
",",
"1.0",
"]",
",",
"distance",
"=",
"2.0",
",",
"scale",
"=",
"0.05",
",",
"keys",
"=",
"' '",
",",
"controller",
"=",
"None",
")",
":",
"text",
"=",
... | Display head-locked message in VR and wait for key press. | [
"Display",
"head",
"-",
"locked",
"message",
"in",
"VR",
"and",
"wait",
"for",
"key",
"press",
"."
] | [
"\"\"\" Display head-locked message in VR and wait for key press.\n \n Args:\n msg (str): Message text\n color: RBG 3-tuple of color values\n distance (float): Z rendering distance from MainView\n scale (float): Text node scaling factor\n keys (str): Key code(s) to dismiss m... | [
{
"param": "msg",
"type": null
},
{
"param": "color",
"type": null
},
{
"param": "distance",
"type": null
},
{
"param": "scale",
"type": null
},
{
"param": "keys",
"type": null
},
{
"param": "controller",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "msg",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "color",
"type": null,
"docstring": "RBG 3-tup... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | addHeadLockedText | <not_specific> | def addHeadLockedText(msg='Text', color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05):
""" Add a head-locked text node, e.g. to display task feedback in VR.
Args:
msg (str): Message text
color: RBG 3-tuple of color values
distance (float): Z rendering distance from MainView
sca... | Add a head-locked text node, e.g. to display task feedback in VR.
Args:
msg (str): Message text
color: RBG 3-tuple of color values
distance (float): Z rendering distance from MainView
scale (float): Text node scaling factor
Returns: Vizard node3d object containing the ... | Add a head-locked text node, e.g. to display task feedback in VR. | [
"Add",
"a",
"head",
"-",
"locked",
"text",
"node",
"e",
".",
"g",
".",
"to",
"display",
"task",
"feedback",
"in",
"VR",
"."
] | def addHeadLockedText(msg='Text', color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05):
text = viz.addText3D(msg, scale=[scale, scale, scale], color=color)
text.resolution(1.0)
text.setThickness(0.1)
text.alignment(viz.ALIGN_CENTER)
text_link = viz.link(viz.MainView, text, enabled=True)
text_link.pr... | [
"def",
"addHeadLockedText",
"(",
"msg",
"=",
"'Text'",
",",
"color",
"=",
"[",
"1.0",
",",
"1.0",
",",
"1.0",
"]",
",",
"distance",
"=",
"2.0",
",",
"scale",
"=",
"0.05",
")",
":",
"text",
"=",
"viz",
".",
"addText3D",
"(",
"msg",
",",
"scale",
"... | Add a head-locked text node, e.g. | [
"Add",
"a",
"head",
"-",
"locked",
"text",
"node",
"e",
".",
"g",
"."
] | [
"\"\"\" Add a head-locked text node, e.g. to display task feedback in VR.\n \n Args:\n msg (str): Message text\n color: RBG 3-tuple of color values\n distance (float): Z rendering distance from MainView\n scale (float): Text node scaling factor\n \n Returns: Vizard node3d obj... | [
{
"param": "msg",
"type": null
},
{
"param": "color",
"type": null
},
{
"param": "distance",
"type": null
},
{
"param": "scale",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "msg",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "color",
"type": null,
"docstring": "RBG 3-tup... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | waitVRInstruction | null | def waitVRInstruction(msg='Text', title='Title', force_str=False,
distance=2.5, height=None, billboard=True,
resolution=(1920, 1080), size=(1.92, 1.08),
font_size=50, keys=' ', controller=None):
""" Display a world-locked instruction panel in VR and... | Display a world-locked instruction panel in VR and wait for key press.
Instructions can be provided as string or read from an external text file.
Default is to show the panel at eye level at a distance of 2.5m. Depending on
text length, you might need to adjust the font and/or canvas size.
Arg... | Display a world-locked instruction panel in VR and wait for key press.
Instructions can be provided as string or read from an external text file.
Default is to show the panel at eye level at a distance of 2.5m. Depending on
text length, you might need to adjust the font and/or canvas size. | [
"Display",
"a",
"world",
"-",
"locked",
"instruction",
"panel",
"in",
"VR",
"and",
"wait",
"for",
"key",
"press",
".",
"Instructions",
"can",
"be",
"provided",
"as",
"string",
"or",
"read",
"from",
"an",
"external",
"text",
"file",
".",
"Default",
"is",
... | def waitVRInstruction(msg='Text', title='Title', force_str=False,
distance=2.5, height=None, billboard=True,
resolution=(1920, 1080), size=(1.92, 1.08),
font_size=50, keys=' ', controller=None):
if not force_str:
try:
with open(m... | [
"def",
"waitVRInstruction",
"(",
"msg",
"=",
"'Text'",
",",
"title",
"=",
"'Title'",
",",
"force_str",
"=",
"False",
",",
"distance",
"=",
"2.5",
",",
"height",
"=",
"None",
",",
"billboard",
"=",
"True",
",",
"resolution",
"=",
"(",
"1920",
",",
"1080... | Display a world-locked instruction panel in VR and wait for key press. | [
"Display",
"a",
"world",
"-",
"locked",
"instruction",
"panel",
"in",
"VR",
"and",
"wait",
"for",
"key",
"press",
"."
] | [
"\"\"\" Display a world-locked instruction panel in VR and wait for key press.\n \n Instructions can be provided as string or read from an external text file. \n Default is to show the panel at eye level at a distance of 2.5m. Depending on \n text length, you might need to adjust the font and/or canvas ... | [
{
"param": "msg",
"type": null
},
{
"param": "title",
"type": null
},
{
"param": "force_str",
"type": null
},
{
"param": "distance",
"type": null
},
{
"param": "height",
"type": null
},
{
"param": "billboard",
"type": null
},
{
"param": "re... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "msg",
"type": null,
"docstring": "One of:\nString: Message text to display on the instruction panel\nValid text file name: File content is read and set as message text",
"docstring_tokens": [
"One",
"of",
... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | addWorldLockedCanvas | <not_specific> | def addWorldLockedCanvas(msg='Text', title='Title', pos=[0, 2, 2], billboard=False,
resolution=(1920, 1080), size=(1.92, 1.08), font_size=50):
""" Add a world-locked text panel, e.g. for experiment instructions.
Convenience function for Vizard's vizinfo functionality with useful VR defa... | Add a world-locked text panel, e.g. for experiment instructions.
Convenience function for Vizard's vizinfo functionality with useful VR defaults.
Args:
msg (str): Initial message text
title (str): Title bar text for InfoPanel
pos (3-tuple): World position for canvas center
... | Add a world-locked text panel, e.g. for experiment instructions.
Convenience function for Vizard's vizinfo functionality with useful VR defaults. | [
"Add",
"a",
"world",
"-",
"locked",
"text",
"panel",
"e",
".",
"g",
".",
"for",
"experiment",
"instructions",
".",
"Convenience",
"function",
"for",
"Vizard",
"'",
"s",
"vizinfo",
"functionality",
"with",
"useful",
"VR",
"defaults",
"."
] | def addWorldLockedCanvas(msg='Text', title='Title', pos=[0, 2, 2], billboard=False,
resolution=(1920, 1080), size=(1.92, 1.08), font_size=50):
canvas = viz.addGUICanvas(align=viz.ALIGN_CENTER)
canvas.setPosition(pos)
canvas.setRenderWorld(resolution=resolution, size=size)
canvas... | [
"def",
"addWorldLockedCanvas",
"(",
"msg",
"=",
"'Text'",
",",
"title",
"=",
"'Title'",
",",
"pos",
"=",
"[",
"0",
",",
"2",
",",
"2",
"]",
",",
"billboard",
"=",
"False",
",",
"resolution",
"=",
"(",
"1920",
",",
"1080",
")",
",",
"size",
"=",
"... | Add a world-locked text panel, e.g. | [
"Add",
"a",
"world",
"-",
"locked",
"text",
"panel",
"e",
".",
"g",
"."
] | [
"\"\"\" Add a world-locked text panel, e.g. for experiment instructions.\n Convenience function for Vizard's vizinfo functionality with useful VR defaults.\n \n Args:\n msg (str): Initial message text\n title (str): Title bar text for InfoPanel\n pos (3-tuple): World position for canva... | [
{
"param": "msg",
"type": null
},
{
"param": "title",
"type": null
},
{
"param": "pos",
"type": null
},
{
"param": "billboard",
"type": null
},
{
"param": "resolution",
"type": null
},
{
"param": "size",
"type": null
},
{
"param": "font_siz... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "msg",
"type": null,
"docstring": "Initial message text",
"docstring_tokens": [
"Initial",
"message",
"text"
],
"default": null,
"is_optional": false
},
{
"identifier": "t... |
773f5d2626fd6328d47cdd2d0905c28b7ea00924 | ischtz/proantireach-vizard | code/vexptoolbox/vrutil.py | [
"MIT"
] | Python | addRayPrimitive | <not_specific> | def addRayPrimitive(origin, direction, length=100, color=viz.RED,
alpha=0.6, linewidth=3, parent=None):
""" Create a Vizard ray primitive from two vertices. Can be used
to e.g. indicate a raycast or gaze vector in a VR environment.
Args:
origin (3-tuple): Ray origin
... | Create a Vizard ray primitive from two vertices. Can be used
to e.g. indicate a raycast or gaze vector in a VR environment.
Args:
origin (3-tuple): Ray origin
direction (3-tuple): Unit direction vector
length (float): Ray length (set to 1 and use direction=<end>
to draw... | Create a Vizard ray primitive from two vertices. Can be used
to e.g. indicate a raycast or gaze vector in a VR environment. | [
"Create",
"a",
"Vizard",
"ray",
"primitive",
"from",
"two",
"vertices",
".",
"Can",
"be",
"used",
"to",
"e",
".",
"g",
".",
"indicate",
"a",
"raycast",
"or",
"gaze",
"vector",
"in",
"a",
"VR",
"environment",
"."
] | def addRayPrimitive(origin, direction, length=100, color=viz.RED,
alpha=0.6, linewidth=3, parent=None):
viz.startLayer(viz.LINES)
viz.lineWidth(linewidth)
viz.vertexColor(color)
viz.vertex(origin)
viz.vertex([x * length for x in direction])
ray = viz.endLayer()
ray.disab... | [
"def",
"addRayPrimitive",
"(",
"origin",
",",
"direction",
",",
"length",
"=",
"100",
",",
"color",
"=",
"viz",
".",
"RED",
",",
"alpha",
"=",
"0.6",
",",
"linewidth",
"=",
"3",
",",
"parent",
"=",
"None",
")",
":",
"viz",
".",
"startLayer",
"(",
"... | Create a Vizard ray primitive from two vertices. | [
"Create",
"a",
"Vizard",
"ray",
"primitive",
"from",
"two",
"vertices",
"."
] | [
"\"\"\" Create a Vizard ray primitive from two vertices. Can be used\n to e.g. indicate a raycast or gaze vector in a VR environment.\n \n Args:\n origin (3-tuple): Ray origin\n direction (3-tuple): Unit direction vector\n length (float): Ray length (set to 1 and use direction=<end>\n ... | [
{
"param": "origin",
"type": null
},
{
"param": "direction",
"type": null
},
{
"param": "length",
"type": null
},
{
"param": "color",
"type": null
},
{
"param": "alpha",
"type": null
},
{
"param": "linewidth",
"type": null
},
{
"param": "pa... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "origin",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "direction",
"type": null,
"docstring": "Un... |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | _set_ui | null | def _set_ui(self):
""" Update GUI elements to display status (if enabled) """
if self._ui is not None:
if len(self._samples) == 0:
self._ui_bar.message('No data')
elif self._frame < len(self._samples):
self._ui_bar.set(float(self._fra... | Update GUI elements to display status (if enabled) | Update GUI elements to display status (if enabled) | [
"Update",
"GUI",
"elements",
"to",
"display",
"status",
"(",
"if",
"enabled",
")"
] | def _set_ui(self):
if self._ui is not None:
if len(self._samples) == 0:
self._ui_bar.message('No data')
elif self._frame < len(self._samples):
self._ui_bar.set(float(self._frame)/float(len(self._samples)))
self._ui_bar.message('{:d}/{:d}'.f... | [
"def",
"_set_ui",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ui",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"self",
".",
"_samples",
")",
"==",
"0",
":",
"self",
".",
"_ui_bar",
".",
"message",
"(",
"'No data'",
")",
"elif",
"self",
".",
"_fra... | Update GUI elements to display status (if enabled) | [
"Update",
"GUI",
"elements",
"to",
"display",
"status",
"(",
"if",
"enabled",
")"
] | [
"\"\"\" Update GUI elements to display status (if enabled) \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | _ui_toggle_replay | null | def _ui_toggle_replay(self):
""" Callback for Play/Pause button """
if self.replaying:
self.stopReplay()
else:
self.startReplay(from_start=False) | Callback for Play/Pause button | Callback for Play/Pause button | [
"Callback",
"for",
"Play",
"/",
"Pause",
"button"
] | def _ui_toggle_replay(self):
if self.replaying:
self.stopReplay()
else:
self.startReplay(from_start=False) | [
"def",
"_ui_toggle_replay",
"(",
"self",
")",
":",
"if",
"self",
".",
"replaying",
":",
"self",
".",
"stopReplay",
"(",
")",
"else",
":",
"self",
".",
"startReplay",
"(",
"from_start",
"=",
"False",
")"
] | Callback for Play/Pause button | [
"Callback",
"for",
"Play",
"/",
"Pause",
"button"
] | [
"\"\"\" Callback for Play/Pause button \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | _update_nodes | null | def _update_nodes(self):
""" Create replay node objects and UI items """
COLORS = {'gaze3d': viz.RED, 'view': viz.BLUE}
# Remove all previous checkbox UI objects
if self._ui is not None:
for node in self._nodes.keys():
self._nodes[node]['ui'].remove()
... | Create replay node objects and UI items | Create replay node objects and UI items | [
"Create",
"replay",
"node",
"objects",
"and",
"UI",
"items"
] | def _update_nodes(self):
COLORS = {'gaze3d': viz.RED, 'view': viz.BLUE}
if self._ui is not None:
for node in self._nodes.keys():
self._nodes[node]['ui'].remove()
self._nodes = {}
for node in self.replay_nodes:
self._nodes[node] = {'visible': True}... | [
"def",
"_update_nodes",
"(",
"self",
")",
":",
"COLORS",
"=",
"{",
"'gaze3d'",
":",
"viz",
".",
"RED",
",",
"'view'",
":",
"viz",
".",
"BLUE",
"}",
"if",
"self",
".",
"_ui",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"_nodes",
".... | Create replay node objects and UI items | [
"Create",
"replay",
"node",
"objects",
"and",
"UI",
"items"
] | [
"\"\"\" Create replay node objects and UI items \"\"\"",
"# Remove all previous checkbox UI objects",
"# Consistent colors for built-in nodes",
"# Generate a random color",
"# Enable / disable gaze settings based on data availability"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | loadRecording | null | def loadRecording(self, sample_file=None, sep='\t'):
""" Load a SampleRecorder sample file for replay
Args:
sample_file (str): Filename of CSV file to load. If no
file is specified, show Vizard file selection dialog.
sep (str): Field separator in CSV inp... | Load a SampleRecorder sample file for replay
Args:
sample_file (str): Filename of CSV file to load. If no
file is specified, show Vizard file selection dialog.
sep (str): Field separator in CSV input file
| Load a SampleRecorder sample file for replay | [
"Load",
"a",
"SampleRecorder",
"sample",
"file",
"for",
"replay"
] | def loadRecording(self, sample_file=None, sep='\t'):
s = []
if sample_file is None:
sample_file = vizinput.fileOpen(filter=[('Samples files', '*.csv;*.tsv;*.dat;*.txt')])
with open(sample_file, 'r') as sf:
reader = csv.DictReader(sf, delimiter=sep)
if len(read... | [
"def",
"loadRecording",
"(",
"self",
",",
"sample_file",
"=",
"None",
",",
"sep",
"=",
"'\\t'",
")",
":",
"s",
"=",
"[",
"]",
"if",
"sample_file",
"is",
"None",
":",
"sample_file",
"=",
"vizinput",
".",
"fileOpen",
"(",
"filter",
"=",
"[",
"(",
"'Sam... | Load a SampleRecorder sample file for replay | [
"Load",
"a",
"SampleRecorder",
"sample",
"file",
"for",
"replay"
] | [
"\"\"\" Load a SampleRecorder sample file for replay\n \n Args:\n sample_file (str): Filename of CSV file to load. If no \n file is specified, show Vizard file selection dialog.\n sep (str): Field separator in CSV input file\n \"\"\"",
"# Convert numeric v... | [
{
"param": "self",
"type": null
},
{
"param": "sample_file",
"type": null
},
{
"param": "sep",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "sample_file",
"type": null,
"docstring": "Filename of CSV file to l... |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | startReplay | null | def startReplay(self, from_start=True):
""" Play the current recording frame by frame
Args:
from_start (bool): if True, start replay from first frame
"""
if from_start or self._frame >= len(self._samples):
self._frame = 0
if self._player is None... | Play the current recording frame by frame
Args:
from_start (bool): if True, start replay from first frame
| Play the current recording frame by frame | [
"Play",
"the",
"current",
"recording",
"frame",
"by",
"frame"
] | def startReplay(self, from_start=True):
if from_start or self._frame >= len(self._samples):
self._frame = 0
if self._player is None:
self._player = vizact.onupdate(0, self.replayCurrentFrame)
if not self.replaying:
self._player.setEnabled(True)
sel... | [
"def",
"startReplay",
"(",
"self",
",",
"from_start",
"=",
"True",
")",
":",
"if",
"from_start",
"or",
"self",
".",
"_frame",
">=",
"len",
"(",
"self",
".",
"_samples",
")",
":",
"self",
".",
"_frame",
"=",
"0",
"if",
"self",
".",
"_player",
"is",
... | Play the current recording frame by frame | [
"Play",
"the",
"current",
"recording",
"frame",
"by",
"frame"
] | [
"\"\"\" Play the current recording frame by frame \n \n Args:\n from_start (bool): if True, start replay from first frame \n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "from_start",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "from_start",
"type": null,
"docstring": "if True, start replay from... |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | resetReplay | null | def resetReplay(self):
""" Stop replay and reset to first frame """
if self.replaying:
self.stopReplay()
self._frame = 0
self._set_ui() | Stop replay and reset to first frame | Stop replay and reset to first frame | [
"Stop",
"replay",
"and",
"reset",
"to",
"first",
"frame"
] | def resetReplay(self):
if self.replaying:
self.stopReplay()
self._frame = 0
self._set_ui() | [
"def",
"resetReplay",
"(",
"self",
")",
":",
"if",
"self",
".",
"replaying",
":",
"self",
".",
"stopReplay",
"(",
")",
"self",
".",
"_frame",
"=",
"0",
"self",
".",
"_set_ui",
"(",
")"
] | Stop replay and reset to first frame | [
"Stop",
"replay",
"and",
"reset",
"to",
"first",
"frame"
] | [
"\"\"\" Stop replay and reset to first frame \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | replayCurrentFrame | null | def replayCurrentFrame(self, advance=True):
""" Replay task. Sets up gaze position for each upcoming frame
Args:
advance (bool): if True, advance to next frame (default).
"""
if self._frame < len(self._samples):
f = self._samples[self._frame]
... | Replay task. Sets up gaze position for each upcoming frame
Args:
advance (bool): if True, advance to next frame (default).
| Replay task. Sets up gaze position for each upcoming frame | [
"Replay",
"task",
".",
"Sets",
"up",
"gaze",
"position",
"for",
"each",
"upcoming",
"frame"
] | def replayCurrentFrame(self, advance=True):
if self._frame < len(self._samples):
f = self._samples[self._frame]
for eye_pos in list(self._gaze.keys()):
if self._gaze[eye_pos]['node'] is not None:
if self._gaze[eye_pos]['data']:
... | [
"def",
"replayCurrentFrame",
"(",
"self",
",",
"advance",
"=",
"True",
")",
":",
"if",
"self",
".",
"_frame",
"<",
"len",
"(",
"self",
".",
"_samples",
")",
":",
"f",
"=",
"self",
".",
"_samples",
"[",
"self",
".",
"_frame",
"]",
"for",
"eye_pos",
... | Replay task. | [
"Replay",
"task",
"."
] | [
"\"\"\" Replay task. Sets up gaze position for each upcoming frame \n \n Args:\n advance (bool): if True, advance to next frame (default).\n \"\"\"",
"# Set up eye representation(s)",
"# Position the 3D gaze cursor and other nodes",
"# Reached last frame, stop replay and reset"... | [
{
"param": "self",
"type": null
},
{
"param": "advance",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "advance",
"type": null,
"docstring": "if True, advance to next fram... |
e80734ee4c18256eb3d8addd18c2d13e4d8beaa2 | ischtz/proantireach-vizard | code/vexptoolbox/replay.py | [
"MIT"
] | Python | replayDone | <not_specific> | def replayDone(self):
""" Returns True if replay is finished,
use as viztask.waitTrue(object.replayDone)
"""
return self.finished | Returns True if replay is finished,
use as viztask.waitTrue(object.replayDone)
| Returns True if replay is finished,
use as viztask.waitTrue(object.replayDone) | [
"Returns",
"True",
"if",
"replay",
"is",
"finished",
"use",
"as",
"viztask",
".",
"waitTrue",
"(",
"object",
".",
"replayDone",
")"
] | def replayDone(self):
return self.finished | [
"def",
"replayDone",
"(",
"self",
")",
":",
"return",
"self",
".",
"finished"
] | Returns True if replay is finished,
use as viztask.waitTrue(object.replayDone) | [
"Returns",
"True",
"if",
"replay",
"is",
"finished",
"use",
"as",
"viztask",
".",
"waitTrue",
"(",
"object",
".",
"replayDone",
")"
] | [
"\"\"\" Returns True if replay is finished,\n use as viztask.waitTrue(object.replayDone)\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | _dlog | null | def _dlog(self, text):
""" Log debug information to console if debug output is enabled
Args:
String to print
"""
if self.debug:
print('[{:s}] {:.4f} - {:s}'.format('EXP', viz.tick(), str(text))) | Log debug information to console if debug output is enabled
Args:
String to print
| Log debug information to console if debug output is enabled
Args:
String to print | [
"Log",
"debug",
"information",
"to",
"console",
"if",
"debug",
"output",
"is",
"enabled",
"Args",
":",
"String",
"to",
"print"
] | def _dlog(self, text):
if self.debug:
print('[{:s}] {:.4f} - {:s}'.format('EXP', viz.tick(), str(text))) | [
"def",
"_dlog",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"'[{:s}] {:.4f} - {:s}'",
".",
"format",
"(",
"'EXP'",
",",
"viz",
".",
"tick",
"(",
")",
",",
"str",
"(",
"text",
")",
")",
")"
] | Log debug information to console if debug output is enabled
Args:
String to print | [
"Log",
"debug",
"information",
"to",
"console",
"if",
"debug",
"output",
"is",
"enabled",
"Args",
":",
"String",
"to",
"print"
] | [
"\"\"\" Log debug information to console if debug output is enabled \n \n Args:\n String to print\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "text",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "text",
"type": null,
"docstring": null,
"docstring_tokens": [... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | output_file_name | <not_specific> | def output_file_name(self):
""" Base file name for output files, including date and time
and participant metadata if available. Generated and cached on
first access. """
if self._base_filename is None:
fn = self.name
if 'id' in self.participant:
... | Base file name for output files, including date and time
and participant metadata if available. Generated and cached on
first access. | Base file name for output files, including date and time
and participant metadata if available. Generated and cached on
first access. | [
"Base",
"file",
"name",
"for",
"output",
"files",
"including",
"date",
"and",
"time",
"and",
"participant",
"metadata",
"if",
"available",
".",
"Generated",
"and",
"cached",
"on",
"first",
"access",
"."
] | def output_file_name(self):
if self._base_filename is None:
fn = self.name
if 'id' in self.participant:
fn += '_' + str(self.participant.id)
if 'session' in self.participant:
fn += '_' + str(self.participant.session)
fn += '_' + tim... | [
"def",
"output_file_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_base_filename",
"is",
"None",
":",
"fn",
"=",
"self",
".",
"name",
"if",
"'id'",
"in",
"self",
".",
"participant",
":",
"fn",
"+=",
"'_'",
"+",
"str",
"(",
"self",
".",
"participa... | Base file name for output files, including date and time
and participant metadata if available. | [
"Base",
"file",
"name",
"for",
"output",
"files",
"including",
"date",
"and",
"time",
"and",
"participant",
"metadata",
"if",
"available",
"."
] | [
"\"\"\" Base file name for output files, including date and time \n and participant metadata if available. Generated and cached on \n first access. \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | addTrials | null | def addTrials(self, num_trials=1, params={}, list_params={}, block=None):
""" Add a specified number of trials. The contents of
the 'params' dict are copied to each trial. You can then further
modify each trial individually using its 'params' attribute.
Args:
num_trials (int... | Add a specified number of trials. The contents of
the 'params' dict are copied to each trial. You can then further
modify each trial individually using its 'params' attribute.
Args:
num_trials (int): Number of trials to create
params (dict): Parameter values to set in a... | Add a specified number of trials. The contents of
the 'params' dict are copied to each trial. You can then further
modify each trial individually using its 'params' attribute. | [
"Add",
"a",
"specified",
"number",
"of",
"trials",
".",
"The",
"contents",
"of",
"the",
"'",
"params",
"'",
"dict",
"are",
"copied",
"to",
"each",
"trial",
".",
"You",
"can",
"then",
"further",
"modify",
"each",
"trial",
"individually",
"using",
"its",
"... | def addTrials(self, num_trials=1, params={}, list_params={}, block=None):
if block is None:
block = 0
for key in list_params.keys():
if len(list_params[key]) != num_trials:
estr = 'Values in list_params must have the same length as num_trials! [{:s}]'
... | [
"def",
"addTrials",
"(",
"self",
",",
"num_trials",
"=",
"1",
",",
"params",
"=",
"{",
"}",
",",
"list_params",
"=",
"{",
"}",
",",
"block",
"=",
"None",
")",
":",
"if",
"block",
"is",
"None",
":",
"block",
"=",
"0",
"for",
"key",
"in",
"list_par... | Add a specified number of trials. | [
"Add",
"a",
"specified",
"number",
"of",
"trials",
"."
] | [
"\"\"\" Add a specified number of trials. The contents of\n the 'params' dict are copied to each trial. You can then further\n modify each trial individually using its 'params' attribute.\n\n Args:\n num_trials (int): Number of trials to create\n params (dict): Parameter v... | [
{
"param": "self",
"type": null
},
{
"param": "num_trials",
"type": null
},
{
"param": "params",
"type": null
},
{
"param": "list_params",
"type": null
},
{
"param": "block",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "num_trials",
"type": null,
"docstring": "Number of trials to create... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | addTrialsFullFactorial | null | def addTrialsFullFactorial(self, levels, repeat=1, params={}, block=None):
""" Add trials by building a full-factorial experimental design.
When given as number of levels, generates a numeric range starting
at 1. Factors are included as params, together with the contents of
the params=... | Add trials by building a full-factorial experimental design.
When given as number of levels, generates a numeric range starting
at 1. Factors are included as params, together with the contents of
the params= attribute.
Args:
levels (dict): Factor names (as keys) and valu... | Add trials by building a full-factorial experimental design.
When given as number of levels, generates a numeric range starting
at 1. Factors are included as params, together with the contents of
the params= attribute. | [
"Add",
"trials",
"by",
"building",
"a",
"full",
"-",
"factorial",
"experimental",
"design",
".",
"When",
"given",
"as",
"number",
"of",
"levels",
"generates",
"a",
"numeric",
"range",
"starting",
"at",
"1",
".",
"Factors",
"are",
"included",
"as",
"params",
... | def addTrialsFullFactorial(self, levels, repeat=1, params={}, block=None):
if block is None:
block = 0
iters = {}
factors = []
variables = list(levels.keys())
for key in variables:
if type(levels[key]) == int:
iters[key] = list(range(1, int... | [
"def",
"addTrialsFullFactorial",
"(",
"self",
",",
"levels",
",",
"repeat",
"=",
"1",
",",
"params",
"=",
"{",
"}",
",",
"block",
"=",
"None",
")",
":",
"if",
"block",
"is",
"None",
":",
"block",
"=",
"0",
"iters",
"=",
"{",
"}",
"factors",
"=",
... | Add trials by building a full-factorial experimental design. | [
"Add",
"trials",
"by",
"building",
"a",
"full",
"-",
"factorial",
"experimental",
"design",
"."
] | [
"\"\"\" Add trials by building a full-factorial experimental design.\n\n When given as number of levels, generates a numeric range starting\n at 1. Factors are included as params, together with the contents of \n the params= attribute. \n\n Args:\n levels (dict): Factor names ... | [
{
"param": "self",
"type": null
},
{
"param": "levels",
"type": null
},
{
"param": "repeat",
"type": null
},
{
"param": "params",
"type": null
},
{
"param": "block",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "levels",
"type": null,
"docstring": "Factor names (as keys) and val... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | addTrialsFromCSV | null | def addTrialsFromCSV(self, file_name=None, sep=None, repeat=1, block=None,
block_col=None, params={}, num_rows=None):
""" Read a list of trials from a CSV file, adding the columns
as parameter values to each trial (one trial per row). If no file is
specified, show Vizar... | Read a list of trials from a CSV file, adding the columns
as parameter values to each trial (one trial per row). If no file is
specified, show Vizard file selection dialog.
Args:
file_name (str): name of CSV file to read, or None to show selection dialog
sep (str): col... | Read a list of trials from a CSV file, adding the columns
as parameter values to each trial (one trial per row). If no file is
specified, show Vizard file selection dialog. | [
"Read",
"a",
"list",
"of",
"trials",
"from",
"a",
"CSV",
"file",
"adding",
"the",
"columns",
"as",
"parameter",
"values",
"to",
"each",
"trial",
"(",
"one",
"trial",
"per",
"row",
")",
".",
"If",
"no",
"file",
"is",
"specified",
"show",
"Vizard",
"file... | def addTrialsFromCSV(self, file_name=None, sep=None, repeat=1, block=None,
block_col=None, params={}, num_rows=None):
if file_name is None:
file_name = vizinput.fileOpen(filter=[('Trial files', '*.csv;*.tsv;*.dat;*.txt')])
if sep is None:
ext = os.path.sp... | [
"def",
"addTrialsFromCSV",
"(",
"self",
",",
"file_name",
"=",
"None",
",",
"sep",
"=",
"None",
",",
"repeat",
"=",
"1",
",",
"block",
"=",
"None",
",",
"block_col",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"num_rows",
"=",
"None",
")",
":",... | Read a list of trials from a CSV file, adding the columns
as parameter values to each trial (one trial per row). | [
"Read",
"a",
"list",
"of",
"trials",
"from",
"a",
"CSV",
"file",
"adding",
"the",
"columns",
"as",
"parameter",
"values",
"to",
"each",
"trial",
"(",
"one",
"trial",
"per",
"row",
")",
"."
] | [
"\"\"\" Read a list of trials from a CSV file, adding the columns\n as parameter values to each trial (one trial per row). If no file is \n specified, show Vizard file selection dialog.\n\n Args:\n file_name (str): name of CSV file to read, or None to show selection dialog\n ... | [
{
"param": "self",
"type": null
},
{
"param": "file_name",
"type": null
},
{
"param": "sep",
"type": null
},
{
"param": "repeat",
"type": null
},
{
"param": "block",
"type": null
},
{
"param": "block_col",
"type": null
},
{
"param": "params... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "file_name",
"type": null,
"docstring": "name of CSV file to read, o... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | clearTrials | null | def clearTrials(self):
""" Remove all current trials from the experiment """
self.trials = []
self._updateBlocks()
self._dlog('Trials cleared.') | Remove all current trials from the experiment | Remove all current trials from the experiment | [
"Remove",
"all",
"current",
"trials",
"from",
"the",
"experiment"
] | def clearTrials(self):
self.trials = []
self._updateBlocks()
self._dlog('Trials cleared.') | [
"def",
"clearTrials",
"(",
"self",
")",
":",
"self",
".",
"trials",
"=",
"[",
"]",
"self",
".",
"_updateBlocks",
"(",
")",
"self",
".",
"_dlog",
"(",
"'Trials cleared.'",
")"
] | Remove all current trials from the experiment | [
"Remove",
"all",
"current",
"trials",
"from",
"the",
"experiment"
] | [
"\"\"\" Remove all current trials from the experiment \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | randomizeTrials | null | def randomizeTrials(self, ignore_blocks=False, shuffle_blocks=False):
""" Shuffle trial order globally or within blocks
Args:
ignore_blocks (bool): if True, shuffle all trials
irrespective of their block number
shuffle_blocks (bool): if True, randomize experime... | Shuffle trial order globally or within blocks
Args:
ignore_blocks (bool): if True, shuffle all trials
irrespective of their block number
shuffle_blocks (bool): if True, randomize experimental
blocks before randomizing trials within blocks
| Shuffle trial order globally or within blocks | [
"Shuffle",
"trial",
"order",
"globally",
"or",
"within",
"blocks"
] | def randomizeTrials(self, ignore_blocks=False, shuffle_blocks=False):
if self._state == STATE_RUNNING:
raise ValueError('Cannot randomize trials while experiment is in progress!')
else:
self._updateBlocks()
if self.trials is not None:
if ignore_blocks:... | [
"def",
"randomizeTrials",
"(",
"self",
",",
"ignore_blocks",
"=",
"False",
",",
"shuffle_blocks",
"=",
"False",
")",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_RUNNING",
":",
"raise",
"ValueError",
"(",
"'Cannot randomize trials while experiment is in progress!'",... | Shuffle trial order globally or within blocks | [
"Shuffle",
"trial",
"order",
"globally",
"or",
"within",
"blocks"
] | [
"\"\"\" Shuffle trial order globally or within blocks \n\n Args:\n ignore_blocks (bool): if True, shuffle all trials \n irrespective of their block number\n shuffle_blocks (bool): if True, randomize experimental\n blocks before randomizing trials within blo... | [
{
"param": "self",
"type": null
},
{
"param": "ignore_blocks",
"type": null
},
{
"param": "shuffle_blocks",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ignore_blocks",
"type": null,
"docstring": "if True, shuffle all tr... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | requestParticipantData | null | def requestParticipantData(self, questions={}, session=True, age=True,
gender=True, expname=True):
""" Show UI to input participant ID and further details.
Must be called as a Vizard task (using yield statement)!
Some common fields are included for standardizati... | Show UI to input participant ID and further details.
Must be called as a Vizard task (using yield statement)!
Some common fields are included for standardization, others can
be added using the questions argument. Participant data is accessible
through the experiment object's .particip... | Show UI to input participant ID and further details.
Must be called as a Vizard task (using yield statement)!
Some common fields are included for standardization, others can
be added using the questions argument. Participant data is accessible
through the experiment object's .participant property. | [
"Show",
"UI",
"to",
"input",
"participant",
"ID",
"and",
"further",
"details",
".",
"Must",
"be",
"called",
"as",
"a",
"Vizard",
"task",
"(",
"using",
"yield",
"statement",
")",
"!",
"Some",
"common",
"fields",
"are",
"included",
"for",
"standardization",
... | def requestParticipantData(self, questions={}, session=True, age=True,
gender=True, expname=True):
if type(questions) in (list, tuple):
questions = {q.replace(' ', ''):q for q in questions}
ui = vizinfo.InfoPanel('Please enter the following data:', title='Part... | [
"def",
"requestParticipantData",
"(",
"self",
",",
"questions",
"=",
"{",
"}",
",",
"session",
"=",
"True",
",",
"age",
"=",
"True",
",",
"gender",
"=",
"True",
",",
"expname",
"=",
"True",
")",
":",
"if",
"type",
"(",
"questions",
")",
"in",
"(",
... | Show UI to input participant ID and further details. | [
"Show",
"UI",
"to",
"input",
"participant",
"ID",
"and",
"further",
"details",
"."
] | [
"\"\"\" Show UI to input participant ID and further details. \n Must be called as a Vizard task (using yield statement)!\n\n Some common fields are included for standardization, others can\n be added using the questions argument. Participant data is accessible\n through the experiment ob... | [
{
"param": "self",
"type": null
},
{
"param": "questions",
"type": null
},
{
"param": "session",
"type": null
},
{
"param": "age",
"type": null
},
{
"param": "gender",
"type": null
},
{
"param": "expname",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "questions",
"type": null,
"docstring": "Further data fields to show... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | addSampleRecorder | null | def addSampleRecorder(self, auto_record=True, **kwargs):
""" Set up sample recorder to record view, gaze, and other
objects' position and orientation on each display frame.
Args:
auto_record (bool): if True, start and stop recording
automatically with each trial
... | Set up sample recorder to record view, gaze, and other
objects' position and orientation on each display frame.
Args:
auto_record (bool): if True, start and stop recording
automatically with each trial
**kwargs: any valid argument to SampleRecorder()
| Set up sample recorder to record view, gaze, and other
objects' position and orientation on each display frame. | [
"Set",
"up",
"sample",
"recorder",
"to",
"record",
"view",
"gaze",
"and",
"other",
"objects",
"'",
"position",
"and",
"orientation",
"on",
"each",
"display",
"frame",
"."
] | def addSampleRecorder(self, auto_record=True, **kwargs):
self._recorder = SampleRecorder(DEBUG=self.debug, **kwargs)
self._auto_record = auto_record | [
"def",
"addSampleRecorder",
"(",
"self",
",",
"auto_record",
"=",
"True",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"_recorder",
"=",
"SampleRecorder",
"(",
"DEBUG",
"=",
"self",
".",
"debug",
",",
"**",
"kwargs",
")",
"self",
".",
"_auto_record",
"=",... | Set up sample recorder to record view, gaze, and other
objects' position and orientation on each display frame. | [
"Set",
"up",
"sample",
"recorder",
"to",
"record",
"view",
"gaze",
"and",
"other",
"objects",
"'",
"position",
"and",
"orientation",
"on",
"each",
"display",
"frame",
"."
] | [
"\"\"\" Set up sample recorder to record view, gaze, and other\n objects' position and orientation on each display frame. \n\n Args:\n auto_record (bool): if True, start and stop recording\n automatically with each trial\n **kwargs: any valid argument to SampleReco... | [
{
"param": "self",
"type": null
},
{
"param": "auto_record",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "auto_record",
"type": null,
"docstring": "if True, start and stop r... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | addSteamVRDebugOverlay | null | def addSteamVRDebugOverlay(self, enable=False, hotkey=viz.KEY_F12):
""" Add a SteamVR debug overlay to the experiment, which can help
measure positions in a virtual environment, determine controller IDs,
etc. Press hotkey to activate (default: F12).
Args:
enable (bo... | Add a SteamVR debug overlay to the experiment, which can help
measure positions in a virtual environment, determine controller IDs,
etc. Press hotkey to activate (default: F12).
Args:
enable (bool): Whether the overlay should be visible from the start
hotkey: A... | Add a SteamVR debug overlay to the experiment, which can help
measure positions in a virtual environment, determine controller IDs,
etc. Press hotkey to activate (default: F12). | [
"Add",
"a",
"SteamVR",
"debug",
"overlay",
"to",
"the",
"experiment",
"which",
"can",
"help",
"measure",
"positions",
"in",
"a",
"virtual",
"environment",
"determine",
"controller",
"IDs",
"etc",
".",
"Press",
"hotkey",
"to",
"activate",
"(",
"default",
":",
... | def addSteamVRDebugOverlay(self, enable=False, hotkey=viz.KEY_F12):
try:
from .steamvr_debug import SteamVRDebugOverlay
self.debugger = SteamVRDebugOverlay(enable=enable, hotkey=hotkey)
except:
print('Could not add SteamVR debug overlay. Is SteamVR installed and acti... | [
"def",
"addSteamVRDebugOverlay",
"(",
"self",
",",
"enable",
"=",
"False",
",",
"hotkey",
"=",
"viz",
".",
"KEY_F12",
")",
":",
"try",
":",
"from",
".",
"steamvr_debug",
"import",
"SteamVRDebugOverlay",
"self",
".",
"debugger",
"=",
"SteamVRDebugOverlay",
"(",... | Add a SteamVR debug overlay to the experiment, which can help
measure positions in a virtual environment, determine controller IDs,
etc. | [
"Add",
"a",
"SteamVR",
"debug",
"overlay",
"to",
"the",
"experiment",
"which",
"can",
"help",
"measure",
"positions",
"in",
"a",
"virtual",
"environment",
"determine",
"controller",
"IDs",
"etc",
"."
] | [
"\"\"\" Add a SteamVR debug overlay to the experiment, which can help\n measure positions in a virtual environment, determine controller IDs, \n etc. Press hotkey to activate (default: F12).\n \n Args:\n enable (bool): Whether the overlay should be visible from the start\n ... | [
{
"param": "self",
"type": null
},
{
"param": "enable",
"type": null
},
{
"param": "hotkey",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "enable",
"type": null,
"docstring": "Whether the overlay should be ... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | _updateBlocks | null | def _updateBlocks(self):
""" Rebuild experiment list of blocks and corresponding trials """
self._blocks = []
self._block_trials = {}
if self.trials is not None and len(self.trials) > 0:
for t in self.trials:
if t.block not in self._blocks:
... | Rebuild experiment list of blocks and corresponding trials | Rebuild experiment list of blocks and corresponding trials | [
"Rebuild",
"experiment",
"list",
"of",
"blocks",
"and",
"corresponding",
"trials"
] | def _updateBlocks(self):
self._blocks = []
self._block_trials = {}
if self.trials is not None and len(self.trials) > 0:
for t in self.trials:
if t.block not in self._blocks:
self._blocks.append(t.block)
if t.block not in self._block... | [
"def",
"_updateBlocks",
"(",
"self",
")",
":",
"self",
".",
"_blocks",
"=",
"[",
"]",
"self",
".",
"_block_trials",
"=",
"{",
"}",
"if",
"self",
".",
"trials",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"trials",
")",
">",
"0",
":",
"fo... | Rebuild experiment list of blocks and corresponding trials | [
"Rebuild",
"experiment",
"list",
"of",
"blocks",
"and",
"corresponding",
"trials"
] | [
"\"\"\" Rebuild experiment list of blocks and corresponding trials \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | startNextTrial | null | def startNextTrial(self, print_summary=True):
""" Start the next trial in the trial list, if any
Args:
print_summary (bool): if True, print out trial status and parameters
"""
if self._trial_running:
raise RuntimeError('Cannot start a trial while another... | Start the next trial in the trial list, if any
Args:
print_summary (bool): if True, print out trial status and parameters
| Start the next trial in the trial list, if any | [
"Start",
"the",
"next",
"trial",
"in",
"the",
"trial",
"list",
"if",
"any"
] | def startNextTrial(self, print_summary=True):
if self._trial_running:
raise RuntimeError('Cannot start a trial while another trial is in progress!')
if self._cur_trial == 0 and not self.trials[self._cur_trial].done:
trial_idx = 0
elif self._cur_trial + 1 >= len(self.tr... | [
"def",
"startNextTrial",
"(",
"self",
",",
"print_summary",
"=",
"True",
")",
":",
"if",
"self",
".",
"_trial_running",
":",
"raise",
"RuntimeError",
"(",
"'Cannot start a trial while another trial is in progress!'",
")",
"if",
"self",
".",
"_cur_trial",
"==",
"0",
... | Start the next trial in the trial list, if any | [
"Start",
"the",
"next",
"trial",
"in",
"the",
"trial",
"list",
"if",
"any"
] | [
"\"\"\" Start the next trial in the trial list, if any \n \n Args:\n print_summary (bool): if True, print out trial status and parameters\n \"\"\"",
"# first trial"
] | [
{
"param": "self",
"type": null
},
{
"param": "print_summary",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "print_summary",
"type": null,
"docstring": "if True, print out tria... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | startTrial | null | def startTrial(self, trial_idx, repeat=False, print_summary=True):
""" Start a specific trial by its index in the trial list,
e.g. the first trial is experiment.trials[0]. By default each
trial is only run once unless repeat is set to True.
Args:
trial_idx: Trial object or ... | Start a specific trial by its index in the trial list,
e.g. the first trial is experiment.trials[0]. By default each
trial is only run once unless repeat is set to True.
Args:
trial_idx: Trial object or index of trial to run
repeat (bool): if True, allow repetition of ... | Start a specific trial by its index in the trial list,
e.g. the first trial is experiment.trials[0]. By default each
trial is only run once unless repeat is set to True. | [
"Start",
"a",
"specific",
"trial",
"by",
"its",
"index",
"in",
"the",
"trial",
"list",
"e",
".",
"g",
".",
"the",
"first",
"trial",
"is",
"experiment",
".",
"trials",
"[",
"0",
"]",
".",
"By",
"default",
"each",
"trial",
"is",
"only",
"run",
"once",
... | def startTrial(self, trial_idx, repeat=False, print_summary=True):
if self._trial_running:
raise RuntimeError('Cannot start a trial while another trial is in progress!')
if type(trial_idx) == Trial:
trial_idx = trial_idx.index
if self.trials[trial_idx].done and not repeat... | [
"def",
"startTrial",
"(",
"self",
",",
"trial_idx",
",",
"repeat",
"=",
"False",
",",
"print_summary",
"=",
"True",
")",
":",
"if",
"self",
".",
"_trial_running",
":",
"raise",
"RuntimeError",
"(",
"'Cannot start a trial while another trial is in progress!'",
")",
... | Start a specific trial by its index in the trial list,
e.g. | [
"Start",
"a",
"specific",
"trial",
"by",
"its",
"index",
"in",
"the",
"trial",
"list",
"e",
".",
"g",
"."
] | [
"\"\"\" Start a specific trial by its index in the trial list,\n e.g. the first trial is experiment.trials[0]. By default each \n trial is only run once unless repeat is set to True.\n\n Args:\n trial_idx: Trial object or index of trial to run\n repeat (bool): if True, all... | [
{
"param": "self",
"type": null
},
{
"param": "trial_idx",
"type": null
},
{
"param": "repeat",
"type": null
},
{
"param": "print_summary",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trial_idx",
"type": null,
"docstring": "Trial object or index of tr... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | run | <not_specific> | def run(self, trial_task, pre_trial_task=None, post_trial_task=None):
""" Run all trials in current order, executing the trial_task each time
All tasks must accept two arguments: experiment and trial, e.g.
def TrialTask(experiment, trial):
yield doSomething
Args:
... | Run all trials in current order, executing the trial_task each time
All tasks must accept two arguments: experiment and trial, e.g.
def TrialTask(experiment, trial):
yield doSomething
Args:
trial_task: Vizard task (containing "yield") to run each trial
... | Run all trials in current order, executing the trial_task each time
All tasks must accept two arguments: experiment and trial, e.g.
def TrialTask(experiment, trial):
yield doSomething | [
"Run",
"all",
"trials",
"in",
"current",
"order",
"executing",
"the",
"trial_task",
"each",
"time",
"All",
"tasks",
"must",
"accept",
"two",
"arguments",
":",
"experiment",
"and",
"trial",
"e",
".",
"g",
".",
"def",
"TrialTask",
"(",
"experiment",
"trial",
... | def run(self, trial_task, pre_trial_task=None, post_trial_task=None):
if self._state == STATE_RUNNING:
raise RuntimeError('The experiment is already running!')
return
if len(self.trials) < 1:
raise RuntimeError('No trials to run!')
return
while not... | [
"def",
"run",
"(",
"self",
",",
"trial_task",
",",
"pre_trial_task",
"=",
"None",
",",
"post_trial_task",
"=",
"None",
")",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_RUNNING",
":",
"raise",
"RuntimeError",
"(",
"'The experiment is already running!'",
")",
... | Run all trials in current order, executing the trial_task each time
All tasks must accept two arguments: experiment and trial, e.g. | [
"Run",
"all",
"trials",
"in",
"current",
"order",
"executing",
"the",
"trial_task",
"each",
"time",
"All",
"tasks",
"must",
"accept",
"two",
"arguments",
":",
"experiment",
"and",
"trial",
"e",
".",
"g",
"."
] | [
"\"\"\" Run all trials in current order, executing the trial_task each time\n \n All tasks must accept two arguments: experiment and trial, e.g.\n def TrialTask(experiment, trial):\n yield doSomething\n\n Args:\n trial_task: Vizard task (containing \"yield\") to run... | [
{
"param": "self",
"type": null
},
{
"param": "trial_task",
"type": null
},
{
"param": "pre_trial_task",
"type": null
},
{
"param": "post_trial_task",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trial_task",
"type": null,
"docstring": "Vizard task (containing \"... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | saveTrialDataToCSV | null | def saveTrialDataToCSV(self, file_name=None, sep='\t', rec_data='single'):
""" Saves trial parameters and results to CSV file
Args:
file_name (str): Name of CSV file to write to
sep (str): Field separator string (default: Tab)
rec_data: How to save sample and event d... | Saves trial parameters and results to CSV file
Args:
file_name (str): Name of CSV file to write to
sep (str): Field separator string (default: Tab)
rec_data: How to save sample and event data if recorded:
- 'single': One large file with all samples (default)... | Saves trial parameters and results to CSV file | [
"Saves",
"trial",
"parameters",
"and",
"results",
"to",
"CSV",
"file"
] | def saveTrialDataToCSV(self, file_name=None, sep='\t', rec_data='single'):
if file_name is None:
file_name = '{:s}.tsv'.format(self.output_file_name)
if type(rec_data) == bool:
if rec_data:
rec_data = 'single'
else:
rec_data = 'none'
... | [
"def",
"saveTrialDataToCSV",
"(",
"self",
",",
"file_name",
"=",
"None",
",",
"sep",
"=",
"'\\t'",
",",
"rec_data",
"=",
"'single'",
")",
":",
"if",
"file_name",
"is",
"None",
":",
"file_name",
"=",
"'{:s}.tsv'",
".",
"format",
"(",
"self",
".",
"output_... | Saves trial parameters and results to CSV file | [
"Saves",
"trial",
"parameters",
"and",
"results",
"to",
"CSV",
"file"
] | [
"\"\"\" Saves trial parameters and results to CSV file\n\n Args:\n file_name (str): Name of CSV file to write to\n sep (str): Field separator string (default: Tab)\n rec_data: How to save sample and event data if recorded:\n - 'single': One large file with all ... | [
{
"param": "self",
"type": null
},
{
"param": "file_name",
"type": null
},
{
"param": "sep",
"type": null
},
{
"param": "rec_data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "file_name",
"type": null,
"docstring": "Name of CSV file to write t... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | toDict | <not_specific> | def toDict(self):
""" Return all experiment data and results as dict """
e = {'name': self.name,
'config': self.config.toDict(),
'participant': self.participant.toDict()}
for trial in self.trials:
if 'trials' not in e.keys():
e['trials'] = [... | Return all experiment data and results as dict | Return all experiment data and results as dict | [
"Return",
"all",
"experiment",
"data",
"and",
"results",
"as",
"dict"
] | def toDict(self):
e = {'name': self.name,
'config': self.config.toDict(),
'participant': self.participant.toDict()}
for trial in self.trials:
if 'trials' not in e.keys():
e['trials'] = []
e['trials'].append(trial.toDict())
if self... | [
"def",
"toDict",
"(",
"self",
")",
":",
"e",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'config'",
":",
"self",
".",
"config",
".",
"toDict",
"(",
")",
",",
"'participant'",
":",
"self",
".",
"participant",
".",
"toDict",
"(",
")",
"}",
... | Return all experiment data and results as dict | [
"Return",
"all",
"experiment",
"data",
"and",
"results",
"as",
"dict"
] | [
"\"\"\" Return all experiment data and results as dict \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | saveExperimentData | null | def saveExperimentData(self, json_file=None):
""" Save all experimental data to JSON file """
if json_file is None:
json_file = self.output_file_name + '.json'
with open(json_file, 'w') as jf:
jf.write(json.dumps(self.toDict()))
self._dlog('Saved experiment data ... | Save all experimental data to JSON file | Save all experimental data to JSON file | [
"Save",
"all",
"experimental",
"data",
"to",
"JSON",
"file"
] | def saveExperimentData(self, json_file=None):
if json_file is None:
json_file = self.output_file_name + '.json'
with open(json_file, 'w') as jf:
jf.write(json.dumps(self.toDict()))
self._dlog('Saved experiment data to {:s}.'.format(str(json_file))) | [
"def",
"saveExperimentData",
"(",
"self",
",",
"json_file",
"=",
"None",
")",
":",
"if",
"json_file",
"is",
"None",
":",
"json_file",
"=",
"self",
".",
"output_file_name",
"+",
"'.json'",
"with",
"open",
"(",
"json_file",
",",
"'w'",
")",
"as",
"jf",
":"... | Save all experimental data to JSON file | [
"Save",
"all",
"experimental",
"data",
"to",
"JSON",
"file"
] | [
"\"\"\" Save all experimental data to JSON file \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "json_file",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "json_file",
"type": null,
"docstring": null,
"docstring_token... |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | status | <not_specific> | def status(self):
""" String description of current trial status """
states = {STATE_NEW: 'not run',
STATE_RUNNING: 'running',
STATE_DONE: 'done'}
return states[self._state] | String description of current trial status | String description of current trial status | [
"String",
"description",
"of",
"current",
"trial",
"status"
] | def status(self):
states = {STATE_NEW: 'not run',
STATE_RUNNING: 'running',
STATE_DONE: 'done'}
return states[self._state] | [
"def",
"status",
"(",
"self",
")",
":",
"states",
"=",
"{",
"STATE_NEW",
":",
"'not run'",
",",
"STATE_RUNNING",
":",
"'running'",
",",
"STATE_DONE",
":",
"'done'",
"}",
"return",
"states",
"[",
"self",
".",
"_state",
"]"
] | String description of current trial status | [
"String",
"description",
"of",
"current",
"trial",
"status"
] | [
"\"\"\" String description of current trial status \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | summary | <not_specific> | def summary(self):
""" Trial summary string. Includes params for a running trial and
results for a finished trial.
"""
value_str = ''
if self.status == 'running' and len(self.params) > 0:
value_str = 'Params: ' + ', '.join(['{:s}={:s}'.format(l, str(res)) for (l, res... | Trial summary string. Includes params for a running trial and
results for a finished trial.
| Trial summary string. Includes params for a running trial and
results for a finished trial. | [
"Trial",
"summary",
"string",
".",
"Includes",
"params",
"for",
"a",
"running",
"trial",
"and",
"results",
"for",
"a",
"finished",
"trial",
"."
] | def summary(self):
value_str = ''
if self.status == 'running' and len(self.params) > 0:
value_str = 'Params: ' + ', '.join(['{:s}={:s}'.format(l, str(res)) for (l, res) in self.params])
elif self.status == 'done' and len(self.results) > 0:
value_str = 'Results: ' + ', '.j... | [
"def",
"summary",
"(",
"self",
")",
":",
"value_str",
"=",
"''",
"if",
"self",
".",
"status",
"==",
"'running'",
"and",
"len",
"(",
"self",
".",
"params",
")",
">",
"0",
":",
"value_str",
"=",
"'Params: '",
"+",
"', '",
".",
"join",
"(",
"[",
"'{:s... | Trial summary string. | [
"Trial",
"summary",
"string",
"."
] | [
"\"\"\" Trial summary string. Includes params for a running trial and \n results for a finished trial.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | starttime | <not_specific> | def starttime(self):
""" Return Vizard time stamp of when this trial was started """
if self._state < STATE_RUNNING:
e = 'Trying to access start time of a trial that has not been started yet!'
raise RuntimeError(e)
else:
return self._start_tick | Return Vizard time stamp of when this trial was started | Return Vizard time stamp of when this trial was started | [
"Return",
"Vizard",
"time",
"stamp",
"of",
"when",
"this",
"trial",
"was",
"started"
] | def starttime(self):
if self._state < STATE_RUNNING:
e = 'Trying to access start time of a trial that has not been started yet!'
raise RuntimeError(e)
else:
return self._start_tick | [
"def",
"starttime",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"<",
"STATE_RUNNING",
":",
"e",
"=",
"'Trying to access start time of a trial that has not been started yet!'",
"raise",
"RuntimeError",
"(",
"e",
")",
"else",
":",
"return",
"self",
".",
"_st... | Return Vizard time stamp of when this trial was started | [
"Return",
"Vizard",
"time",
"stamp",
"of",
"when",
"this",
"trial",
"was",
"started"
] | [
"\"\"\" Return Vizard time stamp of when this trial was started \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | endtime | <not_specific> | def endtime(self):
""" Return Vizard time stamp of when this trial ended """
if self._state < STATE_DONE:
e = 'Trying to access end time of a trial that has not been finished!'
raise RuntimeError(e)
else:
return self._end_tick | Return Vizard time stamp of when this trial ended | Return Vizard time stamp of when this trial ended | [
"Return",
"Vizard",
"time",
"stamp",
"of",
"when",
"this",
"trial",
"ended"
] | def endtime(self):
if self._state < STATE_DONE:
e = 'Trying to access end time of a trial that has not been finished!'
raise RuntimeError(e)
else:
return self._end_tick | [
"def",
"endtime",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"<",
"STATE_DONE",
":",
"e",
"=",
"'Trying to access end time of a trial that has not been finished!'",
"raise",
"RuntimeError",
"(",
"e",
")",
"else",
":",
"return",
"self",
".",
"_end_tick"
] | Return Vizard time stamp of when this trial ended | [
"Return",
"Vizard",
"time",
"stamp",
"of",
"when",
"this",
"trial",
"ended"
] | [
"\"\"\" Return Vizard time stamp of when this trial ended \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | toDict | <not_specific> | def toDict(self):
""" Return all trial information as a dict """
d = {'index': self.index,
'block': self.block,
'status': self.status,
'times': {'start_time': self._start_time,
'start_tick': self._start_tick,
'end_time'... | Return all trial information as a dict | Return all trial information as a dict | [
"Return",
"all",
"trial",
"information",
"as",
"a",
"dict"
] | def toDict(self):
d = {'index': self.index,
'block': self.block,
'status': self.status,
'times': {'start_time': self._start_time,
'start_tick': self._start_tick,
'end_time': self._end_time,
'end_tick': sel... | [
"def",
"toDict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'index'",
":",
"self",
".",
"index",
",",
"'block'",
":",
"self",
".",
"block",
",",
"'status'",
":",
"self",
".",
"status",
",",
"'times'",
":",
"{",
"'start_time'",
":",
"self",
".",
"_start... | Return all trial information as a dict | [
"Return",
"all",
"trial",
"information",
"as",
"a",
"dict"
] | [
"\"\"\" Return all trial information as a dict \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b0ea26bfacac5fe860ff4c7e88685b26008599fb | ischtz/proantireach-vizard | code/vexptoolbox/experiment.py | [
"MIT"
] | Python | toJSONFile | null | def toJSONFile(self, json_file):
""" Save this trial to a JSON file
Args:
json_file (str): Output file name
"""
with open(json_file, 'w') as jf:
jf.write(json.dumps(self.toDict())) | Save this trial to a JSON file
Args:
json_file (str): Output file name
| Save this trial to a JSON file | [
"Save",
"this",
"trial",
"to",
"a",
"JSON",
"file"
] | def toJSONFile(self, json_file):
with open(json_file, 'w') as jf:
jf.write(json.dumps(self.toDict())) | [
"def",
"toJSONFile",
"(",
"self",
",",
"json_file",
")",
":",
"with",
"open",
"(",
"json_file",
",",
"'w'",
")",
"as",
"jf",
":",
"jf",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"toDict",
"(",
")",
")",
")"
] | Save this trial to a JSON file | [
"Save",
"this",
"trial",
"to",
"a",
"JSON",
"file"
] | [
"\"\"\" Save this trial to a JSON file \n\n Args:\n json_file (str): Output file name\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "json_file",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "json_file",
"type": null,
"docstring": "Output file name",
"d... |
988e6c8c34b6b32e3db4d7c08db508286fea59c7 | ischtz/proantireach-vizard | code/vexptoolbox/data.py | [
"MIT"
] | Python | toJSONFile | null | def toJSONFile(self, json_file):
""" Save this ParamSet to a JSON file
Args:
json_file (str): Output file name
"""
with open(json_file, 'w') as jf:
jf.write(json.dumps(self.__dict__)) | Save this ParamSet to a JSON file
Args:
json_file (str): Output file name
| Save this ParamSet to a JSON file | [
"Save",
"this",
"ParamSet",
"to",
"a",
"JSON",
"file"
] | def toJSONFile(self, json_file):
with open(json_file, 'w') as jf:
jf.write(json.dumps(self.__dict__)) | [
"def",
"toJSONFile",
"(",
"self",
",",
"json_file",
")",
":",
"with",
"open",
"(",
"json_file",
",",
"'w'",
")",
"as",
"jf",
":",
"jf",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"__dict__",
")",
")"
] | Save this ParamSet to a JSON file | [
"Save",
"this",
"ParamSet",
"to",
"a",
"JSON",
"file"
] | [
"\"\"\" Save this ParamSet to a JSON file \n \n Args:\n json_file (str): Output file name\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "json_file",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "json_file",
"type": null,
"docstring": "Output file name",
"d... |
988e6c8c34b6b32e3db4d7c08db508286fea59c7 | ischtz/proantireach-vizard | code/vexptoolbox/data.py | [
"MIT"
] | Python | _setResults | null | def _setResults(self, result):
""" Update aggregate result variables based on a dictionary """
self._results = {}
vars = ['acc', 'accX', 'accY', 'sd', 'sdX', 'sdY', 'rmsi', 'rmsiX', 'rmsiY', 'ipd',
'acc_L', 'accX_L', 'accY_L', 'sd_L', 'sdX_L', 'sdY_L', 'rmsi_L', 'rmsiX_L', 'rm... | Update aggregate result variables based on a dictionary | Update aggregate result variables based on a dictionary | [
"Update",
"aggregate",
"result",
"variables",
"based",
"on",
"a",
"dictionary"
] | def _setResults(self, result):
self._results = {}
vars = ['acc', 'accX', 'accY', 'sd', 'sdX', 'sdY', 'rmsi', 'rmsiX', 'rmsiY', 'ipd',
'acc_L', 'accX_L', 'accY_L', 'sd_L', 'sdX_L', 'sdY_L', 'rmsi_L', 'rmsiX_L', 'rmsiY_L',
'acc_R', 'accX_R', 'accY_R', 'sd_R', 'sdX_R', 's... | [
"def",
"_setResults",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"_results",
"=",
"{",
"}",
"vars",
"=",
"[",
"'acc'",
",",
"'accX'",
",",
"'accY'",
",",
"'sd'",
",",
"'sdX'",
",",
"'sdY'",
",",
"'rmsi'",
",",
"'rmsiX'",
",",
"'rmsiY'",
","... | Update aggregate result variables based on a dictionary | [
"Update",
"aggregate",
"result",
"variables",
"based",
"on",
"a",
"dictionary"
] | [
"\"\"\" Update aggregate result variables based on a dictionary \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "result",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "result",
"type": null,
"docstring": null,
"docstring_tokens":... |
988e6c8c34b6b32e3db4d7c08db508286fea59c7 | ischtz/proantireach-vizard | code/vexptoolbox/data.py | [
"MIT"
] | Python | toPickleFile | null | def toPickleFile(self, pickle_file='val_result.pkl'):
""" Save ValidationResult object to a pickle file.
This will enable access to built-in analysis and
plotting methods during later analysis.
Args:
pickle_file (str): Output file name
"""
with op... | Save ValidationResult object to a pickle file.
This will enable access to built-in analysis and
plotting methods during later analysis.
Args:
pickle_file (str): Output file name
| Save ValidationResult object to a pickle file.
This will enable access to built-in analysis and
plotting methods during later analysis. | [
"Save",
"ValidationResult",
"object",
"to",
"a",
"pickle",
"file",
".",
"This",
"will",
"enable",
"access",
"to",
"built",
"-",
"in",
"analysis",
"and",
"plotting",
"methods",
"during",
"later",
"analysis",
"."
] | def toPickleFile(self, pickle_file='val_result.pkl'):
with open(pickle_file, 'wb') as f:
pickle.dump(self, f) | [
"def",
"toPickleFile",
"(",
"self",
",",
"pickle_file",
"=",
"'val_result.pkl'",
")",
":",
"with",
"open",
"(",
"pickle_file",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"self",
",",
"f",
")"
] | Save ValidationResult object to a pickle file. | [
"Save",
"ValidationResult",
"object",
"to",
"a",
"pickle",
"file",
"."
] | [
"\"\"\" Save ValidationResult object to a pickle file. \n \n This will enable access to built-in analysis and \n plotting methods during later analysis. \n\n Args:\n pickle_file (str): Output file name\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "pickle_file",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pickle_file",
"type": null,
"docstring": "Output file name",
... |
988e6c8c34b6b32e3db4d7c08db508286fea59c7 | ischtz/proantireach-vizard | code/vexptoolbox/data.py | [
"MIT"
] | Python | plotAccuracy | null | def plotAccuracy(self):
""" Spatial plot of mean and median accuracy in dataset """
fig = plt.figure()
# One subplot per depth plane
depths = []
for t in self.targets:
if t['d'] not in depths:
depths.append(t['d'])
... | Spatial plot of mean and median accuracy in dataset | Spatial plot of mean and median accuracy in dataset | [
"Spatial",
"plot",
"of",
"mean",
"and",
"median",
"accuracy",
"in",
"dataset"
] | def plotAccuracy(self):
fig = plt.figure()
depths = []
for t in self.targets:
if t['d'] not in depths:
depths.append(t['d'])
axs = {}
c = 1
for d in depths:
ax = fig.add_subplot(1, len(depths), c)... | [
"def",
"plotAccuracy",
"(",
"self",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"depths",
"=",
"[",
"]",
"for",
"t",
"in",
"self",
".",
"targets",
":",
"if",
"t",
"[",
"'d'",
"]",
"not",
"in",
"depths",
":",
"depths",
".",
"append",
"... | Spatial plot of mean and median accuracy in dataset | [
"Spatial",
"plot",
"of",
"mean",
"and",
"median",
"accuracy",
"in",
"dataset"
] | [
"\"\"\" Spatial plot of mean and median accuracy in dataset \"\"\"",
"# One subplot per depth plane"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
988e6c8c34b6b32e3db4d7c08db508286fea59c7 | ischtz/proantireach-vizard | code/vexptoolbox/data.py | [
"MIT"
] | Python | plotPrecision | null | def plotPrecision(self, measure='sd'):
""" Spatial plot of individual samples and SD precision in dataset
Args:
measure (str): 'sd' or 'rmsi'
"""
if measure not in ['sd', 'rmsi']:
raise ValueError('Invalid measure specified.')... | Spatial plot of individual samples and SD precision in dataset
Args:
measure (str): 'sd' or 'rmsi'
| Spatial plot of individual samples and SD precision in dataset | [
"Spatial",
"plot",
"of",
"individual",
"samples",
"and",
"SD",
"precision",
"in",
"dataset"
] | def plotPrecision(self, measure='sd'):
if measure not in ['sd', 'rmsi']:
raise ValueError('Invalid measure specified.')
fig = plt.figure()
depths = []
for t in self.targets:
if t['d'] not in depths:
depths.append(t['d'])... | [
"def",
"plotPrecision",
"(",
"self",
",",
"measure",
"=",
"'sd'",
")",
":",
"if",
"measure",
"not",
"in",
"[",
"'sd'",
",",
"'rmsi'",
"]",
":",
"raise",
"ValueError",
"(",
"'Invalid measure specified.'",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
... | Spatial plot of individual samples and SD precision in dataset | [
"Spatial",
"plot",
"of",
"individual",
"samples",
"and",
"SD",
"precision",
"in",
"dataset"
] | [
"\"\"\" Spatial plot of individual samples and SD precision in dataset \n \n Args:\n measure (str): 'sd' or 'rmsi'\n \"\"\"",
"# One subplot per depth plane"
] | [
{
"param": "self",
"type": null
},
{
"param": "measure",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "measure",
"type": null,
"docstring": "'sd' or 'rmsi'",
"docst... |
3402b3ede07603ee8091ffa4e188fe457673c2ad | KyleBringmans/Pac-Man | featureExtractors.py | [
"MIT"
] | Python | closestFood | <not_specific> | def closestFood(pos, food, walls):
"""
closestFood -- this is similar to the function that we have
worked on in the search project; here its all in one place
"""
fringe = [(pos[0], pos[1], 0)]
expanded = set()
while fringe:
pos_x, pos_y, dist = fringe.pop(0)
if (pos_x, pos_y)... |
closestFood -- this is similar to the function that we have
worked on in the search project; here its all in one place
| - this is similar to the function that we have
worked on in the search project; here its all in one place | [
"-",
"this",
"is",
"similar",
"to",
"the",
"function",
"that",
"we",
"have",
"worked",
"on",
"in",
"the",
"search",
"project",
";",
"here",
"its",
"all",
"in",
"one",
"place"
] | def closestFood(pos, food, walls):
fringe = [(pos[0], pos[1], 0)]
expanded = set()
while fringe:
pos_x, pos_y, dist = fringe.pop(0)
if (pos_x, pos_y) in expanded:
continue
expanded.add((pos_x, pos_y))
if food[pos_x][pos_y]:
return dist
nbrs = A... | [
"def",
"closestFood",
"(",
"pos",
",",
"food",
",",
"walls",
")",
":",
"fringe",
"=",
"[",
"(",
"pos",
"[",
"0",
"]",
",",
"pos",
"[",
"1",
"]",
",",
"0",
")",
"]",
"expanded",
"=",
"set",
"(",
")",
"while",
"fringe",
":",
"pos_x",
",",
"pos_... | closestFood -- this is similar to the function that we have
worked on in the search project; here its all in one place | [
"closestFood",
"--",
"this",
"is",
"similar",
"to",
"the",
"function",
"that",
"we",
"have",
"worked",
"on",
"in",
"the",
"search",
"project",
";",
"here",
"its",
"all",
"in",
"one",
"place"
] | [
"\"\"\"\n closestFood -- this is similar to the function that we have\n worked on in the search project; here its all in one place\n \"\"\"",
"# if we find a food at this location then exit",
"# otherwise spread out from the location to its neighbours",
"# no food found"
] | [
{
"param": "pos",
"type": null
},
{
"param": "food",
"type": null
},
{
"param": "walls",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pos",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "food",
"type": null,
"docstring": null,
"docstring_tokens": []... |
c9459d2243c3c7a19a71fe2f85e57249fa51cdac | KyleBringmans/Pac-Man | valueIterationAgents.py | [
"MIT"
] | Python | computeQValueFromValues | <not_specific> | def computeQValueFromValues(self, state, action):
"""
Compute the Q-value of action in state from the
value function stored in self.values.
"""
tot = 0
for nextState, prob in self.mdp.getTransitionStatesAndProbs(state, action):
tot += prob * (self.mdp.getR... |
Compute the Q-value of action in state from the
value function stored in self.values.
| Compute the Q-value of action in state from the
value function stored in self.values. | [
"Compute",
"the",
"Q",
"-",
"value",
"of",
"action",
"in",
"state",
"from",
"the",
"value",
"function",
"stored",
"in",
"self",
".",
"values",
"."
] | def computeQValueFromValues(self, state, action):
tot = 0
for nextState, prob in self.mdp.getTransitionStatesAndProbs(state, action):
tot += prob * (self.mdp.getReward(state, action, nextState) + (self.discount * self.values[nextState]))
return tot | [
"def",
"computeQValueFromValues",
"(",
"self",
",",
"state",
",",
"action",
")",
":",
"tot",
"=",
"0",
"for",
"nextState",
",",
"prob",
"in",
"self",
".",
"mdp",
".",
"getTransitionStatesAndProbs",
"(",
"state",
",",
"action",
")",
":",
"tot",
"+=",
"pro... | Compute the Q-value of action in state from the
value function stored in self.values. | [
"Compute",
"the",
"Q",
"-",
"value",
"of",
"action",
"in",
"state",
"from",
"the",
"value",
"function",
"stored",
"in",
"self",
".",
"values",
"."
] | [
"\"\"\"\n Compute the Q-value of action in state from the\n value function stored in self.values.\n \"\"\"",
"# P * (R + gamma * Val)"
] | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": null
},
{
"param": "action",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": null,
"docstring": null,
"docstring_tokens": ... |
c9459d2243c3c7a19a71fe2f85e57249fa51cdac | KyleBringmans/Pac-Man | valueIterationAgents.py | [
"MIT"
] | Python | computeActionFromValues | <not_specific> | def computeActionFromValues(self, state):
"""
The policy is the best action in the given state
according to the values currently stored in self.values.
You may break ties any way you see fit. Note that if
there are no legal actions, which is the case at the
te... |
The policy is the best action in the given state
according to the values currently stored in self.values.
You may break ties any way you see fit. Note that if
there are no legal actions, which is the case at the
terminal state, you should return None.
| The policy is the best action in the given state
according to the values currently stored in self.values.
You may break ties any way you see fit. Note that if
there are no legal actions, which is the case at the
terminal state, you should return None. | [
"The",
"policy",
"is",
"the",
"best",
"action",
"in",
"the",
"given",
"state",
"according",
"to",
"the",
"values",
"currently",
"stored",
"in",
"self",
".",
"values",
".",
"You",
"may",
"break",
"ties",
"any",
"way",
"you",
"see",
"fit",
".",
"Note",
"... | def computeActionFromValues(self, state):
value = float("-inf")
choice = None
if self.mdp.isTerminal(state):
return None
for action in self.mdp.getPossibleActions(state):
qVal = self.computeQValueFromValues(state, action)
if qVal >= value:
... | [
"def",
"computeActionFromValues",
"(",
"self",
",",
"state",
")",
":",
"value",
"=",
"float",
"(",
"\"-inf\"",
")",
"choice",
"=",
"None",
"if",
"self",
".",
"mdp",
".",
"isTerminal",
"(",
"state",
")",
":",
"return",
"None",
"for",
"action",
"in",
"se... | The policy is the best action in the given state
according to the values currently stored in self.values. | [
"The",
"policy",
"is",
"the",
"best",
"action",
"in",
"the",
"given",
"state",
"according",
"to",
"the",
"values",
"currently",
"stored",
"in",
"self",
".",
"values",
"."
] | [
"\"\"\"\n The policy is the best action in the given state\n according to the values currently stored in self.values.\n\n You may break ties any way you see fit. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return None... | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": null,
"docstring": null,
"docstring_tokens": ... |
6ee48d8edaf70c117c517f95988097e697d2a4b9 | KyleBringmans/Pac-Man | qlearningAgents.py | [
"MIT"
] | Python | computeValueFromQValues | <not_specific> | def computeValueFromQValues(self, state):
"""
Returns max_action Q(state,action)
where the max is over legal actions. Note that if
there are no legal actions, which is the case at the
terminal state, you should return a value of 0.0.
"""
if len(self.getLe... |
Returns max_action Q(state,action)
where the max is over legal actions. Note that if
there are no legal actions, which is the case at the
terminal state, you should return a value of 0.0.
| Returns max_action Q(state,action)
where the max is over legal actions. Note that if
there are no legal actions, which is the case at the
terminal state, you should return a value of 0.0. | [
"Returns",
"max_action",
"Q",
"(",
"state",
"action",
")",
"where",
"the",
"max",
"is",
"over",
"legal",
"actions",
".",
"Note",
"that",
"if",
"there",
"are",
"no",
"legal",
"actions",
"which",
"is",
"the",
"case",
"at",
"the",
"terminal",
"state",
"you"... | def computeValueFromQValues(self, state):
if len(self.getLegalActions(state)) == 0:
return 0.0
tempVals = util.Counter()
for action in self.getLegalActions(state):
tempVals[(action)] = self.getQValue(state,action)
return tempVals[tempVals.argMax()] | [
"def",
"computeValueFromQValues",
"(",
"self",
",",
"state",
")",
":",
"if",
"len",
"(",
"self",
".",
"getLegalActions",
"(",
"state",
")",
")",
"==",
"0",
":",
"return",
"0.0",
"tempVals",
"=",
"util",
".",
"Counter",
"(",
")",
"for",
"action",
"in",
... | Returns max_action Q(state,action)
where the max is over legal actions. | [
"Returns",
"max_action",
"Q",
"(",
"state",
"action",
")",
"where",
"the",
"max",
"is",
"over",
"legal",
"actions",
"."
] | [
"\"\"\"\n Returns max_action Q(state,action)\n where the max is over legal actions. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return a value of 0.0.\n \"\"\"",
"# check for terminal state",
"# calculate q-values f... | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": null,
"docstring": null,
"docstring_tokens": ... |
6ee48d8edaf70c117c517f95988097e697d2a4b9 | KyleBringmans/Pac-Man | qlearningAgents.py | [
"MIT"
] | Python | computeActionFromQValues | <not_specific> | def computeActionFromQValues(self, state):
"""
Compute the best action to take in a state. Note that if there
are no legal actions, which is the case at the terminal state,
you should return None.
"""
actionVals = self.getLegalActions(state)
if len(action... |
Compute the best action to take in a state. Note that if there
are no legal actions, which is the case at the terminal state,
you should return None.
| Compute the best action to take in a state. Note that if there
are no legal actions, which is the case at the terminal state,
you should return None. | [
"Compute",
"the",
"best",
"action",
"to",
"take",
"in",
"a",
"state",
".",
"Note",
"that",
"if",
"there",
"are",
"no",
"legal",
"actions",
"which",
"is",
"the",
"case",
"at",
"the",
"terminal",
"state",
"you",
"should",
"return",
"None",
"."
] | def computeActionFromQValues(self, state):
actionVals = self.getLegalActions(state)
if len(actionVals) == 0:
return None
tempVals = util.Counter()
for action in actionVals:
tempVals[action] = self.getQValue(state, action)
return tempVals.argMax() | [
"def",
"computeActionFromQValues",
"(",
"self",
",",
"state",
")",
":",
"actionVals",
"=",
"self",
".",
"getLegalActions",
"(",
"state",
")",
"if",
"len",
"(",
"actionVals",
")",
"==",
"0",
":",
"return",
"None",
"tempVals",
"=",
"util",
".",
"Counter",
... | Compute the best action to take in a state. | [
"Compute",
"the",
"best",
"action",
"to",
"take",
"in",
"a",
"state",
"."
] | [
"\"\"\"\n Compute the best action to take in a state. Note that if there\n are no legal actions, which is the case at the terminal state,\n you should return None.\n \"\"\"",
"# store q-values in here"
] | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": null,
"docstring": null,
"docstring_tokens": ... |
6ee48d8edaf70c117c517f95988097e697d2a4b9 | KyleBringmans/Pac-Man | qlearningAgents.py | [
"MIT"
] | Python | update | null | def update(self, state, action, nextState, reward):
"""
The parent class calls this to observe a
state = action => nextState and reward transition.
You should do your Q-Value update here
NOTE: You should never call this function,
it will be called on your behal... |
The parent class calls this to observe a
state = action => nextState and reward transition.
You should do your Q-Value update here
NOTE: You should never call this function,
it will be called on your behalf
| The parent class calls this to observe a
state = action => nextState and reward transition.
You should do your Q-Value update here
You should never call this function,
it will be called on your behalf | [
"The",
"parent",
"class",
"calls",
"this",
"to",
"observe",
"a",
"state",
"=",
"action",
"=",
">",
"nextState",
"and",
"reward",
"transition",
".",
"You",
"should",
"do",
"your",
"Q",
"-",
"Value",
"update",
"here",
"You",
"should",
"never",
"call",
"thi... | def update(self, state, action, nextState, reward):
self.qValues[(state,action)] = (1-self.alpha) * self.getQValue(state,action) + self.alpha * (reward + self.discount * self.computeValueFromQValues(nextState)) | [
"def",
"update",
"(",
"self",
",",
"state",
",",
"action",
",",
"nextState",
",",
"reward",
")",
":",
"self",
".",
"qValues",
"[",
"(",
"state",
",",
"action",
")",
"]",
"=",
"(",
"1",
"-",
"self",
".",
"alpha",
")",
"*",
"self",
".",
"getQValue"... | The parent class calls this to observe a
state = action => nextState and reward transition. | [
"The",
"parent",
"class",
"calls",
"this",
"to",
"observe",
"a",
"state",
"=",
"action",
"=",
">",
"nextState",
"and",
"reward",
"transition",
"."
] | [
"\"\"\"\n The parent class calls this to observe a\n state = action => nextState and reward transition.\n You should do your Q-Value update here\n\n NOTE: You should never call this function,\n it will be called on your behalf\n \"\"\"",
"# Q(s,a) = (1-a) * Q(s,... | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": null
},
{
"param": "action",
"type": null
},
{
"param": "nextState",
"type": null
},
{
"param": "reward",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": null,
"docstring": null,
"docstring_tokens": ... |
6ee48d8edaf70c117c517f95988097e697d2a4b9 | KyleBringmans/Pac-Man | qlearningAgents.py | [
"MIT"
] | Python | update | null | def update(self, state, action, nextState, reward):
"""
Should update your weights based on transition
"""
features = self.featExtractor.getFeatures(state,action)
difference = reward + self.discount * self.computeValueFromQValues(nextState) - self.getQValue(state,action) # se... |
Should update your weights based on transition
| Should update your weights based on transition | [
"Should",
"update",
"your",
"weights",
"based",
"on",
"transition"
] | def update(self, state, action, nextState, reward):
features = self.featExtractor.getFeatures(state,action)
difference = reward + self.discount * self.computeValueFromQValues(nextState) - self.getQValue(state,action)
useOtherVector = False
p = state.data.agentStates[0].configuration.po... | [
"def",
"update",
"(",
"self",
",",
"state",
",",
"action",
",",
"nextState",
",",
"reward",
")",
":",
"features",
"=",
"self",
".",
"featExtractor",
".",
"getFeatures",
"(",
"state",
",",
"action",
")",
"difference",
"=",
"reward",
"+",
"self",
".",
"d... | Should update your weights based on transition | [
"Should",
"update",
"your",
"weights",
"based",
"on",
"transition"
] | [
"\"\"\"\n Should update your weights based on transition\n \"\"\"",
"# seperate because it doesn't work otherwise :///",
"# w_i + alfa * difference * f_i(s,a)"
] | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": null
},
{
"param": "action",
"type": null
},
{
"param": "nextState",
"type": null
},
{
"param": "reward",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": null,
"docstring": null,
"docstring_tokens": ... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showOrderDetails | <not_specific> | def showOrderDetails(self, trading_pair, order_id):
"""Show details for an offer."""
uri = f'{self.apibase}{trading_pair}/orders/public/details/{order_id}'
params = {'trading_pair': trading_pair, 'order_id': order_id}
avail_params = ['trading_pair', 'order_id']
p = ParameterBuild... | Show details for an offer. | Show details for an offer. | [
"Show",
"details",
"for",
"an",
"offer",
"."
] | def showOrderDetails(self, trading_pair, order_id):
uri = f'{self.apibase}{trading_pair}/orders/public/details/{order_id}'
params = {'trading_pair': trading_pair, 'order_id': order_id}
avail_params = ['trading_pair', 'order_id']
p = ParameterBuilder({}, {}, uri)
p.verify_keys_and... | [
"def",
"showOrderDetails",
"(",
"self",
",",
"trading_pair",
",",
"order_id",
")",
":",
"uri",
"=",
"f'{self.apibase}{trading_pair}/orders/public/details/{order_id}'",
"params",
"=",
"{",
"'trading_pair'",
":",
"trading_pair",
",",
"'order_id'",
":",
"order_id",
"}",
... | Show details for an offer. | [
"Show",
"details",
"for",
"an",
"offer",
"."
] | [
"\"\"\"Show details for an offer.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "trading_pair",
"type": null
},
{
"param": "order_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trading_pair",
"type": null,
"docstring": null,
"docstring_to... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showMyOrders | <not_specific> | def showMyOrders(self, **args):
"""Query and Filter own Orders."""
# Build parameters
params = args
avail_params = ['type', 'trading_pair', 'state',
'date_start', 'date_end', 'page']
if params.get("trading_pair"):
uri = f'{self.apibase}{params[... | Query and Filter own Orders. | Query and Filter own Orders. | [
"Query",
"and",
"Filter",
"own",
"Orders",
"."
] | def showMyOrders(self, **args):
params = args
avail_params = ['type', 'trading_pair', 'state',
'date_start', 'date_end', 'page']
if params.get("trading_pair"):
uri = f'{self.apibase}{params["trading_pair"]}/orders'
del params["trading_pair"]
... | [
"def",
"showMyOrders",
"(",
"self",
",",
"**",
"args",
")",
":",
"params",
"=",
"args",
"avail_params",
"=",
"[",
"'type'",
",",
"'trading_pair'",
",",
"'state'",
",",
"'date_start'",
",",
"'date_end'",
",",
"'page'",
"]",
"if",
"params",
".",
"get",
"("... | Query and Filter own Orders. | [
"Query",
"and",
"Filter",
"own",
"Orders",
"."
] | [
"\"\"\"Query and Filter own Orders.\"\"\"",
"# Build parameters"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showMyOrderDetails | <not_specific> | def showMyOrderDetails(self, trading_pair, order_id):
"""Details to an own Order."""
uri = f'{self.apibase}{trading_pair}/orders/{order_id}'
p = ParameterBuilder({}, {}, uri)
return self.APIConnect('GET', p) | Details to an own Order. | Details to an own Order. | [
"Details",
"to",
"an",
"own",
"Order",
"."
] | def showMyOrderDetails(self, trading_pair, order_id):
uri = f'{self.apibase}{trading_pair}/orders/{order_id}'
p = ParameterBuilder({}, {}, uri)
return self.APIConnect('GET', p) | [
"def",
"showMyOrderDetails",
"(",
"self",
",",
"trading_pair",
",",
"order_id",
")",
":",
"uri",
"=",
"f'{self.apibase}{trading_pair}/orders/{order_id}'",
"p",
"=",
"ParameterBuilder",
"(",
"{",
"}",
",",
"{",
"}",
",",
"uri",
")",
"return",
"self",
".",
"APIC... | Details to an own Order. | [
"Details",
"to",
"an",
"own",
"Order",
"."
] | [
"\"\"\"Details to an own Order.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "trading_pair",
"type": null
},
{
"param": "order_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trading_pair",
"type": null,
"docstring": null,
"docstring_to... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | executeTrade | <not_specific> | def executeTrade(self, trading_pair, order_id, order_type, amount):
"""Buy/Sell on a specific Order."""
uri = f'{self.apibase}{trading_pair}/trades/{order_id}'
params = { 'type': order_type,
'amount_currency_to_trade': amount}
avail_params = ['type', 'amount_currency_t... | Buy/Sell on a specific Order. | Buy/Sell on a specific Order. | [
"Buy",
"/",
"Sell",
"on",
"a",
"specific",
"Order",
"."
] | def executeTrade(self, trading_pair, order_id, order_type, amount):
uri = f'{self.apibase}{trading_pair}/trades/{order_id}'
params = { 'type': order_type,
'amount_currency_to_trade': amount}
avail_params = ['type', 'amount_currency_to_trade']
p = ParameterBuilder(avail... | [
"def",
"executeTrade",
"(",
"self",
",",
"trading_pair",
",",
"order_id",
",",
"order_type",
",",
"amount",
")",
":",
"uri",
"=",
"f'{self.apibase}{trading_pair}/trades/{order_id}'",
"params",
"=",
"{",
"'type'",
":",
"order_type",
",",
"'amount_currency_to_trade'",
... | Buy/Sell on a specific Order. | [
"Buy",
"/",
"Sell",
"on",
"a",
"specific",
"Order",
"."
] | [
"\"\"\"Buy/Sell on a specific Order.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "trading_pair",
"type": null
},
{
"param": "order_id",
"type": null
},
{
"param": "order_type",
"type": null
},
{
"param": "amount",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trading_pair",
"type": null,
"docstring": null,
"docstring_to... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showMyTrades | <not_specific> | def showMyTrades(self, **args):
"""Query and Filter on past Trades."""
# Build parameters
params = args
avail_params = ['type', 'trading_pair', 'state',
'only_trades_with_action_for_payment_or_transfer_required',
'payment_method', 'date_sta... | Query and Filter on past Trades. | Query and Filter on past Trades. | [
"Query",
"and",
"Filter",
"on",
"past",
"Trades",
"."
] | def showMyTrades(self, **args):
params = args
avail_params = ['type', 'trading_pair', 'state',
'only_trades_with_action_for_payment_or_transfer_required',
'payment_method', 'date_start', 'date_end', 'page']
if params.get("trading_pair"):
... | [
"def",
"showMyTrades",
"(",
"self",
",",
"**",
"args",
")",
":",
"params",
"=",
"args",
"avail_params",
"=",
"[",
"'type'",
",",
"'trading_pair'",
",",
"'state'",
",",
"'only_trades_with_action_for_payment_or_transfer_required'",
",",
"'payment_method'",
",",
"'date... | Query and Filter on past Trades. | [
"Query",
"and",
"Filter",
"on",
"past",
"Trades",
"."
] | [
"\"\"\"Query and Filter on past Trades.\"\"\"",
"# Build parameters"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showMyTradeDetails | <not_specific> | def showMyTradeDetails(self, trading_pair, trade_id):
"""Details to a specific Trade."""
params = {'trading_pair': trading_pair, 'trade_id': trade_id}
avail_params = [ 'trading_pair', 'trade_id' ]
uri = f'{self.apibase}{trading_pair}/trades/{trade_id}'
p = ParameterBuilder({}, {}... | Details to a specific Trade. | Details to a specific Trade. | [
"Details",
"to",
"a",
"specific",
"Trade",
"."
] | def showMyTradeDetails(self, trading_pair, trade_id):
params = {'trading_pair': trading_pair, 'trade_id': trade_id}
avail_params = [ 'trading_pair', 'trade_id' ]
uri = f'{self.apibase}{trading_pair}/trades/{trade_id}'
p = ParameterBuilder({}, {}, uri)
p.verify_keys_and_values(ava... | [
"def",
"showMyTradeDetails",
"(",
"self",
",",
"trading_pair",
",",
"trade_id",
")",
":",
"params",
"=",
"{",
"'trading_pair'",
":",
"trading_pair",
",",
"'trade_id'",
":",
"trade_id",
"}",
"avail_params",
"=",
"[",
"'trading_pair'",
",",
"'trade_id'",
"]",
"u... | Details to a specific Trade. | [
"Details",
"to",
"a",
"specific",
"Trade",
"."
] | [
"\"\"\"Details to a specific Trade.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "trading_pair",
"type": null
},
{
"param": "trade_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trading_pair",
"type": null,
"docstring": null,
"docstring_to... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showOrderbookCompact | <not_specific> | def showOrderbookCompact(self, trading_pair):
"""Bids and Asks in compact format."""
params = {'trading_pair': trading_pair}
avail_params = ['trading_pair']
uri = f'{self.apibase}{trading_pair}/orderbook/compact'
# Build parameters
p = ParameterBuilder({}, {}, uri)
... | Bids and Asks in compact format. | Bids and Asks in compact format. | [
"Bids",
"and",
"Asks",
"in",
"compact",
"format",
"."
] | def showOrderbookCompact(self, trading_pair):
params = {'trading_pair': trading_pair}
avail_params = ['trading_pair']
uri = f'{self.apibase}{trading_pair}/orderbook/compact'
p = ParameterBuilder({}, {}, uri)
p.verify_keys_and_values(avail_params, params)
return self.APICo... | [
"def",
"showOrderbookCompact",
"(",
"self",
",",
"trading_pair",
")",
":",
"params",
"=",
"{",
"'trading_pair'",
":",
"trading_pair",
"}",
"avail_params",
"=",
"[",
"'trading_pair'",
"]",
"uri",
"=",
"f'{self.apibase}{trading_pair}/orderbook/compact'",
"p",
"=",
"Pa... | Bids and Asks in compact format. | [
"Bids",
"and",
"Asks",
"in",
"compact",
"format",
"."
] | [
"\"\"\"Bids and Asks in compact format.\"\"\"",
"# Build parameters"
] | [
{
"param": "self",
"type": null
},
{
"param": "trading_pair",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trading_pair",
"type": null,
"docstring": null,
"docstring_to... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showPublicTradeHistory | <not_specific> | def showPublicTradeHistory(self, trading_pair, **args):
"""All successful trades of the last 24 hours."""
params = { 'trading_pair': trading_pair }
params.update(args)
avail_params = ['trading_pair', 'since_tid']
uri = f'{self.apibase}{trading_pair}/trades/history'
if par... | All successful trades of the last 24 hours. | All successful trades of the last 24 hours. | [
"All",
"successful",
"trades",
"of",
"the",
"last",
"24",
"hours",
"."
] | def showPublicTradeHistory(self, trading_pair, **args):
params = { 'trading_pair': trading_pair }
params.update(args)
avail_params = ['trading_pair', 'since_tid']
uri = f'{self.apibase}{trading_pair}/trades/history'
if params.get('since_tid'):
del params["trading_pair... | [
"def",
"showPublicTradeHistory",
"(",
"self",
",",
"trading_pair",
",",
"**",
"args",
")",
":",
"params",
"=",
"{",
"'trading_pair'",
":",
"trading_pair",
"}",
"params",
".",
"update",
"(",
"args",
")",
"avail_params",
"=",
"[",
"'trading_pair'",
",",
"'sinc... | All successful trades of the last 24 hours. | [
"All",
"successful",
"trades",
"of",
"the",
"last",
"24",
"hours",
"."
] | [
"\"\"\"All successful trades of the last 24 hours.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "trading_pair",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trading_pair",
"type": null,
"docstring": null,
"docstring_to... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showRates | <not_specific> | def showRates(self, trading_pair):
"""Query of the average rate last 3 and 12 hours."""
uri = f'{self.apibase}{trading_pair}/rates'
params = {'trading_pair': trading_pair}
avail_params = ['trading_pair']
# Build parameters
p = ParameterBuilder({}, {}, uri)
p.verif... | Query of the average rate last 3 and 12 hours. | Query of the average rate last 3 and 12 hours. | [
"Query",
"of",
"the",
"average",
"rate",
"last",
"3",
"and",
"12",
"hours",
"."
] | def showRates(self, trading_pair):
uri = f'{self.apibase}{trading_pair}/rates'
params = {'trading_pair': trading_pair}
avail_params = ['trading_pair']
p = ParameterBuilder({}, {}, uri)
p.verify_keys_and_values(avail_params, params)
return self.APIConnect('GET', p) | [
"def",
"showRates",
"(",
"self",
",",
"trading_pair",
")",
":",
"uri",
"=",
"f'{self.apibase}{trading_pair}/rates'",
"params",
"=",
"{",
"'trading_pair'",
":",
"trading_pair",
"}",
"avail_params",
"=",
"[",
"'trading_pair'",
"]",
"p",
"=",
"ParameterBuilder",
"(",... | Query of the average rate last 3 and 12 hours. | [
"Query",
"of",
"the",
"average",
"rate",
"last",
"3",
"and",
"12",
"hours",
"."
] | [
"\"\"\"Query of the average rate last 3 and 12 hours.\"\"\"",
"# Build parameters"
] | [
{
"param": "self",
"type": null
},
{
"param": "trading_pair",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "trading_pair",
"type": null,
"docstring": null,
"docstring_to... |
26eb2282360de50862cb2a74308760b8d4c4619a | buchvC/btcde | btcde.py | [
"MIT"
] | Python | showPermissions | <not_specific> | def showPermissions(self):
"""Show permissions that are allowed for used API key"""
uri = f'{self.apibase}permissions'
p = ParameterBuilder({}, {}, uri)
return self.APIConnect('GET', p) | Show permissions that are allowed for used API key | Show permissions that are allowed for used API key | [
"Show",
"permissions",
"that",
"are",
"allowed",
"for",
"used",
"API",
"key"
] | def showPermissions(self):
uri = f'{self.apibase}permissions'
p = ParameterBuilder({}, {}, uri)
return self.APIConnect('GET', p) | [
"def",
"showPermissions",
"(",
"self",
")",
":",
"uri",
"=",
"f'{self.apibase}permissions'",
"p",
"=",
"ParameterBuilder",
"(",
"{",
"}",
",",
"{",
"}",
",",
"uri",
")",
"return",
"self",
".",
"APIConnect",
"(",
"'GET'",
",",
"p",
")"
] | Show permissions that are allowed for used API key | [
"Show",
"permissions",
"that",
"are",
"allowed",
"for",
"used",
"API",
"key"
] | [
"\"\"\"Show permissions that are allowed for used API key\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
eb1cc9e3e8b70143e866880fceacd8985c5f5f78 | adrifloresm/NeMo | nemo/collections/asr/data_layer.py | [
"Apache-2.0"
] | Python | _process_augmentations | AudioAugmentor | def _process_augmentations(augmenter) -> AudioAugmentor:
"""Process list of online data augmentations.
Accepts either an AudioAugmentor object with pre-defined augmentations,
or a dictionary that points to augmentations that have been defined.
If a dictionary is passed, must follow the below structure... | Process list of online data augmentations.
Accepts either an AudioAugmentor object with pre-defined augmentations,
or a dictionary that points to augmentations that have been defined.
If a dictionary is passed, must follow the below structure:
Dict[str, Dict[str, Any]]: Which refers to a dictionary of... | Process list of online data augmentations.
Accepts either an AudioAugmentor object with pre-defined augmentations,
or a dictionary that points to augmentations that have been defined.
If a dictionary is passed, must follow the below structure:
Dict[str, Dict[str, Any]]: Which refers to a dictionary of string
names for... | [
"Process",
"list",
"of",
"online",
"data",
"augmentations",
".",
"Accepts",
"either",
"an",
"AudioAugmentor",
"object",
"with",
"pre",
"-",
"defined",
"augmentations",
"or",
"a",
"dictionary",
"that",
"points",
"to",
"augmentations",
"that",
"have",
"been",
"def... | def _process_augmentations(augmenter) -> AudioAugmentor:
if isinstance(augmenter, AudioAugmentor):
return augmenter
if not type(augmenter) == dict:
raise ValueError("Cannot parse augmenter. Must be a dict or an AudioAugmentor object ")
augmenter = copy.deepcopy(augmenter)
augmentations =... | [
"def",
"_process_augmentations",
"(",
"augmenter",
")",
"->",
"AudioAugmentor",
":",
"if",
"isinstance",
"(",
"augmenter",
",",
"AudioAugmentor",
")",
":",
"return",
"augmenter",
"if",
"not",
"type",
"(",
"augmenter",
")",
"==",
"dict",
":",
"raise",
"ValueErr... | Process list of online data augmentations. | [
"Process",
"list",
"of",
"online",
"data",
"augmentations",
"."
] | [
"\"\"\"Process list of online data augmentations.\n\n Accepts either an AudioAugmentor object with pre-defined augmentations,\n or a dictionary that points to augmentations that have been defined.\n\n If a dictionary is passed, must follow the below structure:\n Dict[str, Dict[str, Any]]: Which refers t... | [
{
"param": "augmenter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "augmenter",
"type": null,
"docstring": "AudioAugmentor object or\ndictionary of str -> kwargs (dict) which is parsed and used\nto initialize an AudioAugmentor.\nNote: It is crucial that each individual augmentation has\na keyword `p... |
eb1cc9e3e8b70143e866880fceacd8985c5f5f78 | adrifloresm/NeMo | nemo/collections/asr/data_layer.py | [
"Apache-2.0"
] | Python | output_ports | <not_specific> | def output_ports(self):
"""Returns definitions of module output ports.
"""
return {
# 'audio_signal': NeuralType({0: AxisType(BatchTag), 1: AxisType(TimeTag)}),
# 'a_sig_length': NeuralType({0: AxisType(BatchTag)}),
# 'transcripts': NeuralType({0: AxisType(Bat... | Returns definitions of module output ports.
| Returns definitions of module output ports. | [
"Returns",
"definitions",
"of",
"module",
"output",
"ports",
"."
] | def output_ports(self):
return {
'audio_signal': NeuralType(
('B', 'T'),
AudioSignal(freq=self._sample_rate)
if self is not None and self._sample_rate is not None
else AudioSignal(),
),
'a_sig_length': NeuralType... | [
"def",
"output_ports",
"(",
"self",
")",
":",
"return",
"{",
"'audio_signal'",
":",
"NeuralType",
"(",
"(",
"'B'",
",",
"'T'",
")",
",",
"AudioSignal",
"(",
"freq",
"=",
"self",
".",
"_sample_rate",
")",
"if",
"self",
"is",
"not",
"None",
"and",
"self"... | Returns definitions of module output ports. | [
"Returns",
"definitions",
"of",
"module",
"output",
"ports",
"."
] | [
"\"\"\"Returns definitions of module output ports.\n \"\"\"",
"# 'audio_signal': NeuralType({0: AxisType(BatchTag), 1: AxisType(TimeTag)}),",
"# 'a_sig_length': NeuralType({0: AxisType(BatchTag)}),",
"# 'transcripts': NeuralType({0: AxisType(BatchTag), 1: AxisType(TimeTag)}),",
"# 'transcript_length'... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
eb1cc9e3e8b70143e866880fceacd8985c5f5f78 | adrifloresm/NeMo | nemo/collections/asr/data_layer.py | [
"Apache-2.0"
] | Python | output_ports | <not_specific> | def output_ports(self):
"""Returns definitions of module output ports.
"""
return {
# 'processed_signal': NeuralType(
# {0: AxisType(BatchTag), 1: AxisType(SpectrogramSignalTag), 2: AxisType(ProcessedTimeTag),}
# ),
# 'processed_length': Neura... | Returns definitions of module output ports.
| Returns definitions of module output ports. | [
"Returns",
"definitions",
"of",
"module",
"output",
"ports",
"."
] | def output_ports(self):
return {
'processed_signal': NeuralType(('B', 'D', 'T'), SpectrogramType()),
'transcripts': NeuralType(('B', 'T'), ChannelType()),
'transcript_length': NeuralType(tuple('B'), LengthsType()),
} | [
"def",
"output_ports",
"(",
"self",
")",
":",
"return",
"{",
"'processed_signal'",
":",
"NeuralType",
"(",
"(",
"'B'",
",",
"'D'",
",",
"'T'",
")",
",",
"SpectrogramType",
"(",
")",
")",
",",
"'transcripts'",
":",
"NeuralType",
"(",
"(",
"'B'",
",",
"'... | Returns definitions of module output ports. | [
"Returns",
"definitions",
"of",
"module",
"output",
"ports",
"."
] | [
"\"\"\"Returns definitions of module output ports.\n\n\n \"\"\"",
"# 'processed_signal': NeuralType(",
"# {0: AxisType(BatchTag), 1: AxisType(SpectrogramSignalTag), 2: AxisType(ProcessedTimeTag),}",
"# ),",
"# 'processed_length': NeuralType({0: AxisType(BatchTag)}),",
"# 'transcripts': NeuralTyp... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
eb1cc9e3e8b70143e866880fceacd8985c5f5f78 | adrifloresm/NeMo | nemo/collections/asr/data_layer.py | [
"Apache-2.0"
] | Python | output_ports | <not_specific> | def output_ports(self):
"""Returns definitions of module output ports.
"""
return {
'audio_signal': NeuralType(('B', 'T'), AudioSignal(freq=self._sample_rate)),
'a_sig_length': NeuralType(tuple('B'), LengthsType()),
'label': NeuralType(tuple('B'), LabelsType()... | Returns definitions of module output ports.
| Returns definitions of module output ports. | [
"Returns",
"definitions",
"of",
"module",
"output",
"ports",
"."
] | def output_ports(self):
return {
'audio_signal': NeuralType(('B', 'T'), AudioSignal(freq=self._sample_rate)),
'a_sig_length': NeuralType(tuple('B'), LengthsType()),
'label': NeuralType(tuple('B'), LabelsType()),
'label_length': NeuralType(tuple('B'), LengthsType()... | [
"def",
"output_ports",
"(",
"self",
")",
":",
"return",
"{",
"'audio_signal'",
":",
"NeuralType",
"(",
"(",
"'B'",
",",
"'T'",
")",
",",
"AudioSignal",
"(",
"freq",
"=",
"self",
".",
"_sample_rate",
")",
")",
",",
"'a_sig_length'",
":",
"NeuralType",
"("... | Returns definitions of module output ports. | [
"Returns",
"definitions",
"of",
"module",
"output",
"ports",
"."
] | [
"\"\"\"Returns definitions of module output ports.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
8d2608276f06f129e34debebf17e8d3b4688b8fc | adrifloresm/NeMo | nemo/collections/asr/helpers.py | [
"Apache-2.0"
] | Python | __ctc_decoder_predictions_tensor | <not_specific> | def __ctc_decoder_predictions_tensor(tensor, labels):
"""
Decodes a sequence of labels to words
"""
blank_id = len(labels)
hypotheses = []
labels_map = dict([(i, labels[i]) for i in range(len(labels))])
prediction_cpu_tensor = tensor.long().cpu()
# iterate over batch
for ind in range... |
Decodes a sequence of labels to words
| Decodes a sequence of labels to words | [
"Decodes",
"a",
"sequence",
"of",
"labels",
"to",
"words"
] | def __ctc_decoder_predictions_tensor(tensor, labels):
blank_id = len(labels)
hypotheses = []
labels_map = dict([(i, labels[i]) for i in range(len(labels))])
prediction_cpu_tensor = tensor.long().cpu()
for ind in range(prediction_cpu_tensor.shape[0]):
prediction = prediction_cpu_tensor[ind].n... | [
"def",
"__ctc_decoder_predictions_tensor",
"(",
"tensor",
",",
"labels",
")",
":",
"blank_id",
"=",
"len",
"(",
"labels",
")",
"hypotheses",
"=",
"[",
"]",
"labels_map",
"=",
"dict",
"(",
"[",
"(",
"i",
",",
"labels",
"[",
"i",
"]",
")",
"for",
"i",
... | Decodes a sequence of labels to words | [
"Decodes",
"a",
"sequence",
"of",
"labels",
"to",
"words"
] | [
"\"\"\"\n Decodes a sequence of labels to words\n \"\"\"",
"# iterate over batch",
"# CTC decoding procedure",
"# id of a blank symbol"
] | [
{
"param": "tensor",
"type": null
},
{
"param": "labels",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "tensor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "labels",
"type": null,
"docstring": null,
"docstring_tokens... |
8d2608276f06f129e34debebf17e8d3b4688b8fc | adrifloresm/NeMo | nemo/collections/asr/helpers.py | [
"Apache-2.0"
] | Python | monitor_asr_train_progress | null | def monitor_asr_train_progress(tensors: list, labels: list, eval_metric='WER', tb_logger=None):
"""
Takes output of greedy ctc decoder and performs ctc decoding algorithm to
remove duplicates and special symbol. Prints sample to screen, computes
and logs AVG WER to console and (optionally) Tensorboard
... |
Takes output of greedy ctc decoder and performs ctc decoding algorithm to
remove duplicates and special symbol. Prints sample to screen, computes
and logs AVG WER to console and (optionally) Tensorboard
Args:
tensors: A list of 3 tensors (predictions, targets, target_lengths)
labels: A list... | Takes output of greedy ctc decoder and performs ctc decoding algorithm to
remove duplicates and special symbol. Prints sample to screen, computes
and logs AVG WER to console and (optionally) Tensorboard | [
"Takes",
"output",
"of",
"greedy",
"ctc",
"decoder",
"and",
"performs",
"ctc",
"decoding",
"algorithm",
"to",
"remove",
"duplicates",
"and",
"special",
"symbol",
".",
"Prints",
"sample",
"to",
"screen",
"computes",
"and",
"logs",
"AVG",
"WER",
"to",
"console",... | def monitor_asr_train_progress(tensors: list, labels: list, eval_metric='WER', tb_logger=None):
references = []
labels_map = dict([(i, labels[i]) for i in range(len(labels))])
with torch.no_grad():
targets_cpu_tensor = tensors[2].long().cpu()
tgt_lenths_cpu_tensor = tensors[3].long().cpu()
... | [
"def",
"monitor_asr_train_progress",
"(",
"tensors",
":",
"list",
",",
"labels",
":",
"list",
",",
"eval_metric",
"=",
"'WER'",
",",
"tb_logger",
"=",
"None",
")",
":",
"references",
"=",
"[",
"]",
"labels_map",
"=",
"dict",
"(",
"[",
"(",
"i",
",",
"l... | Takes output of greedy ctc decoder and performs ctc decoding algorithm to
remove duplicates and special symbol. | [
"Takes",
"output",
"of",
"greedy",
"ctc",
"decoder",
"and",
"performs",
"ctc",
"decoding",
"algorithm",
"to",
"remove",
"duplicates",
"and",
"special",
"symbol",
"."
] | [
"\"\"\"\n Takes output of greedy ctc decoder and performs ctc decoding algorithm to\n remove duplicates and special symbol. Prints sample to screen, computes\n and logs AVG WER to console and (optionally) Tensorboard\n Args:\n tensors: A list of 3 tensors (predictions, targets, target_lengths)\n ... | [
{
"param": "tensors",
"type": "list"
},
{
"param": "labels",
"type": "list"
},
{
"param": "eval_metric",
"type": null
},
{
"param": "tb_logger",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "tensors",
"type": "list",
"docstring": "A list of 3 tensors (predictions, targets, target_lengths)",
"docstring_tok... |
8d2608276f06f129e34debebf17e8d3b4688b8fc | adrifloresm/NeMo | nemo/collections/asr/helpers.py | [
"Apache-2.0"
] | Python | monitor_classification_training_progress | null | def monitor_classification_training_progress(tensors: list, eval_metric=None, tb_logger=None):
"""
Computes the top k classification accuracy of the model being trained.
Prints sample to screen, computes and and logs a list of top k accuracies
to console and (optionally) Tensorboard
Args:
ten... |
Computes the top k classification accuracy of the model being trained.
Prints sample to screen, computes and and logs a list of top k accuracies
to console and (optionally) Tensorboard
Args:
tensors: A list of 3 tensors (loss, logits, targets)
eval_metric: An optional list of integers deta... | Computes the top k classification accuracy of the model being trained.
Prints sample to screen, computes and and logs a list of top k accuracies
to console and (optionally) Tensorboard | [
"Computes",
"the",
"top",
"k",
"classification",
"accuracy",
"of",
"the",
"model",
"being",
"trained",
".",
"Prints",
"sample",
"to",
"screen",
"computes",
"and",
"and",
"logs",
"a",
"list",
"of",
"top",
"k",
"accuracies",
"to",
"console",
"and",
"(",
"opt... | def monitor_classification_training_progress(tensors: list, eval_metric=None, tb_logger=None):
if eval_metric is None:
eval_metric = [1]
if type(eval_metric) not in (list, tuple):
eval_metric = [eval_metric]
top_k = eval_metric
with torch.no_grad():
logits, targets = tensors[1:]
... | [
"def",
"monitor_classification_training_progress",
"(",
"tensors",
":",
"list",
",",
"eval_metric",
"=",
"None",
",",
"tb_logger",
"=",
"None",
")",
":",
"if",
"eval_metric",
"is",
"None",
":",
"eval_metric",
"=",
"[",
"1",
"]",
"if",
"type",
"(",
"eval_metr... | Computes the top k classification accuracy of the model being trained. | [
"Computes",
"the",
"top",
"k",
"classification",
"accuracy",
"of",
"the",
"model",
"being",
"trained",
"."
] | [
"\"\"\"\n Computes the top k classification accuracy of the model being trained.\n Prints sample to screen, computes and and logs a list of top k accuracies\n to console and (optionally) Tensorboard\n Args:\n tensors: A list of 3 tensors (loss, logits, targets)\n eval_metric: An optional list... | [
{
"param": "tensors",
"type": "list"
},
{
"param": "eval_metric",
"type": null
},
{
"param": "tb_logger",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "tensors",
"type": "list",
"docstring": "A list of 3 tensors (loss, logits, targets)",
"docstring_tokens": [
... |
8d2608276f06f129e34debebf17e8d3b4688b8fc | adrifloresm/NeMo | nemo/collections/asr/helpers.py | [
"Apache-2.0"
] | Python | process_evaluation_epoch | <not_specific> | def process_evaluation_epoch(global_vars: dict, eval_metric='WER', tag=None):
"""
Calculates the aggregated loss and WER across the entire evaluation dataset
"""
eloss = torch.mean(torch.stack(global_vars['EvalLoss'])).item()
hypotheses = global_vars['predictions']
references = global_vars['tran... |
Calculates the aggregated loss and WER across the entire evaluation dataset
| Calculates the aggregated loss and WER across the entire evaluation dataset | [
"Calculates",
"the",
"aggregated",
"loss",
"and",
"WER",
"across",
"the",
"entire",
"evaluation",
"dataset"
] | def process_evaluation_epoch(global_vars: dict, eval_metric='WER', tag=None):
eloss = torch.mean(torch.stack(global_vars['EvalLoss'])).item()
hypotheses = global_vars['predictions']
references = global_vars['transcripts']
eval_metric = eval_metric.upper()
if eval_metric not in {'WER', 'CER'}:
... | [
"def",
"process_evaluation_epoch",
"(",
"global_vars",
":",
"dict",
",",
"eval_metric",
"=",
"'WER'",
",",
"tag",
"=",
"None",
")",
":",
"eloss",
"=",
"torch",
".",
"mean",
"(",
"torch",
".",
"stack",
"(",
"global_vars",
"[",
"'EvalLoss'",
"]",
")",
")",... | Calculates the aggregated loss and WER across the entire evaluation dataset | [
"Calculates",
"the",
"aggregated",
"loss",
"and",
"WER",
"across",
"the",
"entire",
"evaluation",
"dataset"
] | [
"\"\"\"\n Calculates the aggregated loss and WER across the entire evaluation dataset\n \"\"\""
] | [
{
"param": "global_vars",
"type": "dict"
},
{
"param": "eval_metric",
"type": null
},
{
"param": "tag",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "global_vars",
"type": "dict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "eval_metric",
"type": null,
"docstring": null,
"docs... |
8d2608276f06f129e34debebf17e8d3b4688b8fc | adrifloresm/NeMo | nemo/collections/asr/helpers.py | [
"Apache-2.0"
] | Python | process_classification_evaluation_epoch | <not_specific> | def process_classification_evaluation_epoch(global_vars: dict, eval_metric=None, tag=None):
"""
Calculates the aggregated loss and WER across the entire evaluation dataset
"""
if eval_metric is None:
eval_metric = [1]
if type(eval_metric) not in (list, tuple):
eval_metric = [eval_me... |
Calculates the aggregated loss and WER across the entire evaluation dataset
| Calculates the aggregated loss and WER across the entire evaluation dataset | [
"Calculates",
"the",
"aggregated",
"loss",
"and",
"WER",
"across",
"the",
"entire",
"evaluation",
"dataset"
] | def process_classification_evaluation_epoch(global_vars: dict, eval_metric=None, tag=None):
if eval_metric is None:
eval_metric = [1]
if type(eval_metric) not in (list, tuple):
eval_metric = [eval_metric]
top_k = eval_metric
eloss = torch.mean(torch.stack(global_vars['EvalLoss'])).item()... | [
"def",
"process_classification_evaluation_epoch",
"(",
"global_vars",
":",
"dict",
",",
"eval_metric",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"eval_metric",
"is",
"None",
":",
"eval_metric",
"=",
"[",
"1",
"]",
"if",
"type",
"(",
"eval_metric"... | Calculates the aggregated loss and WER across the entire evaluation dataset | [
"Calculates",
"the",
"aggregated",
"loss",
"and",
"WER",
"across",
"the",
"entire",
"evaluation",
"dataset"
] | [
"\"\"\"\n Calculates the aggregated loss and WER across the entire evaluation dataset\n \"\"\""
] | [
{
"param": "global_vars",
"type": "dict"
},
{
"param": "eval_metric",
"type": null
},
{
"param": "tag",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "global_vars",
"type": "dict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "eval_metric",
"type": null,
"docstring": null,
"docs... |
196a5a538020c493a7b8467bb50dcf25a21b021c | hoferbeck/fritzcollectd | tests/test_fritzcollectd.py | [
"MIT"
] | Python | reset_mock | null | def reset_mock(self):
""" Reset values and mock calls. Must be called for every test. """
del self.values[:]
self.info.reset_mock()
self.warning.reset_mock() | Reset values and mock calls. Must be called for every test. | Reset values and mock calls. Must be called for every test. | [
"Reset",
"values",
"and",
"mock",
"calls",
".",
"Must",
"be",
"called",
"for",
"every",
"test",
"."
] | def reset_mock(self):
del self.values[:]
self.info.reset_mock()
self.warning.reset_mock() | [
"def",
"reset_mock",
"(",
"self",
")",
":",
"del",
"self",
".",
"values",
"[",
":",
"]",
"self",
".",
"info",
".",
"reset_mock",
"(",
")",
"self",
".",
"warning",
".",
"reset_mock",
"(",
")"
] | Reset values and mock calls. | [
"Reset",
"values",
"and",
"mock",
"calls",
"."
] | [
"\"\"\" Reset values and mock calls. Must be called for every test. \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
196a5a538020c493a7b8467bb50dcf25a21b021c | hoferbeck/fritzcollectd | tests/test_fritzcollectd.py | [
"MIT"
] | Python | process | null | def process(self, config=None):
""" Simulates collectd. Call callbacks once. """
if config is None:
config = CollectdConfig()
try:
self._cb_config(config)
self._cb_init()
self._cb_read()
finally:
# Make sure read also can be cal... | Simulates collectd. Call callbacks once. | Simulates collectd. Call callbacks once. | [
"Simulates",
"collectd",
".",
"Call",
"callbacks",
"once",
"."
] | def process(self, config=None):
if config is None:
config = CollectdConfig()
try:
self._cb_config(config)
self._cb_init()
self._cb_read()
finally:
self._cb_read()
self._cb_shutdown() | [
"def",
"process",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"CollectdConfig",
"(",
")",
"try",
":",
"self",
".",
"_cb_config",
"(",
"config",
")",
"self",
".",
"_cb_init",
"(",
")",
"self",
... | Simulates collectd. | [
"Simulates",
"collectd",
"."
] | [
"\"\"\" Simulates collectd. Call callbacks once. \"\"\"",
"# Make sure read also can be called if init failed before."
] | [
{
"param": "self",
"type": null
},
{
"param": "config",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "config",
"type": null,
"docstring": null,
"docstring_tokens":... |
196a5a538020c493a7b8467bb50dcf25a21b021c | hoferbeck/fritzcollectd | tests/test_fritzcollectd.py | [
"MIT"
] | Python | fc_class_mock | null | def fc_class_mock(mocker):
"""Fixture that sets up a mocked FritzConnection class."""
result = mocker.patch('fritzconnection.FritzConnection', autospec=True)
result.return_value = FritzConnectionMock()
yield result | Fixture that sets up a mocked FritzConnection class. | Fixture that sets up a mocked FritzConnection class. | [
"Fixture",
"that",
"sets",
"up",
"a",
"mocked",
"FritzConnection",
"class",
"."
] | def fc_class_mock(mocker):
result = mocker.patch('fritzconnection.FritzConnection', autospec=True)
result.return_value = FritzConnectionMock()
yield result | [
"def",
"fc_class_mock",
"(",
"mocker",
")",
":",
"result",
"=",
"mocker",
".",
"patch",
"(",
"'fritzconnection.FritzConnection'",
",",
"autospec",
"=",
"True",
")",
"result",
".",
"return_value",
"=",
"FritzConnectionMock",
"(",
")",
"yield",
"result"
] | Fixture that sets up a mocked FritzConnection class. | [
"Fixture",
"that",
"sets",
"up",
"a",
"mocked",
"FritzConnection",
"class",
"."
] | [
"\"\"\"Fixture that sets up a mocked FritzConnection class.\"\"\""
] | [
{
"param": "mocker",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "mocker",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
84dc7a9f525680762ea7fb238326a1e4f89bf8b9 | hoferbeck/fritzcollectd | fritzcollectd/__init__.py | [
"MIT"
] | Python | init | null | def init(self):
""" Initialize the connection to the FRITZ!Box """
self._fc = fritzconnection.FritzConnection(
address=self._fritz_address, port=self._fritz_port,
user=self._fritz_user, password=self._fritz_password)
if self._fc.modelname is None:
self._fc = N... | Initialize the connection to the FRITZ!Box | Initialize the connection to the FRITZ!Box | [
"Initialize",
"the",
"connection",
"to",
"the",
"FRITZ!Box"
] | def init(self):
self._fc = fritzconnection.FritzConnection(
address=self._fritz_address, port=self._fritz_port,
user=self._fritz_user, password=self._fritz_password)
if self._fc.modelname is None:
self._fc = None
raise IOError("fritzcollectd: Failed to con... | [
"def",
"init",
"(",
"self",
")",
":",
"self",
".",
"_fc",
"=",
"fritzconnection",
".",
"FritzConnection",
"(",
"address",
"=",
"self",
".",
"_fritz_address",
",",
"port",
"=",
"self",
".",
"_fritz_port",
",",
"user",
"=",
"self",
".",
"_fritz_user",
",",... | Initialize the connection to the FRITZ!Box | [
"Initialize",
"the",
"connection",
"to",
"the",
"FRITZ!Box"
] | [
"\"\"\" Initialize the connection to the FRITZ!Box \"\"\"",
"# If the 'Allow access for applications' option is disabled,",
"# the connection behaves as if it was created without password."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
5ca0b6987f49303252cc22b471e6e589a929abbc | abhinavsp0730/elegy | elegy/metrics/binary_accuracy.py | [
"Apache-2.0"
] | Python | binary_accuracy | np.ndarray | def binary_accuracy(
y_true: np.ndarray, y_pred: np.ndarray, threshold: float = 0.5
) -> np.ndarray:
"""
Calculates how often predictions matches binary labels.
Standalone usage:
```python
y_true = np.array([[1], [1], [0], [0]])
y_pred = np.array([[1], [1], [0], [0]])
m = elegy.metrics... |
Calculates how often predictions matches binary labels.
Standalone usage:
```python
y_true = np.array([[1], [1], [0], [0]])
y_pred = np.array([[1], [1], [0], [0]])
m = elegy.metrics.binary_accuracy(y_true, y_pred)
assert m.shape == (4,)
```
Arguments:
y_true: Ground truth ... | Calculates how often predictions matches binary labels.
Standalone usage.
| [
"Calculates",
"how",
"often",
"predictions",
"matches",
"binary",
"labels",
".",
"Standalone",
"usage",
"."
] | def binary_accuracy(
y_true: np.ndarray, y_pred: np.ndarray, threshold: float = 0.5
) -> np.ndarray:
assert abs(y_pred.ndim - y_true.ndim) <= 1
y_true, y_pred = utils.maybe_expand_dims(y_true, y_pred)
y_pred = y_pred > threshold
return jnp.mean(y_true == y_pred, axis=-1) | [
"def",
"binary_accuracy",
"(",
"y_true",
":",
"np",
".",
"ndarray",
",",
"y_pred",
":",
"np",
".",
"ndarray",
",",
"threshold",
":",
"float",
"=",
"0.5",
")",
"->",
"np",
".",
"ndarray",
":",
"assert",
"abs",
"(",
"y_pred",
".",
"ndim",
"-",
"y_true"... | Calculates how often predictions matches binary labels. | [
"Calculates",
"how",
"often",
"predictions",
"matches",
"binary",
"labels",
"."
] | [
"\"\"\"\n Calculates how often predictions matches binary labels.\n\n Standalone usage:\n\n ```python\n y_true = np.array([[1], [1], [0], [0]])\n y_pred = np.array([[1], [1], [0], [0]])\n m = elegy.metrics.binary_accuracy(y_true, y_pred)\n assert m.shape == (4,)\n ```\n Arguments:\n ... | [
{
"param": "y_true",
"type": "np.ndarray"
},
{
"param": "y_pred",
"type": "np.ndarray"
},
{
"param": "threshold",
"type": "float"
}
] | {
"returns": [
{
"docstring": "Binary accuracy values. shape = `[batch_size, d0, ..",
"docstring_tokens": [
"Binary",
"accuracy",
"values",
".",
"shape",
"=",
"`",
"[",
"batch_size",
"d0",
".."
],
"type... |
a4c358be0a80fcb8868a2d25663cac65bf87a828 | abhinavsp0730/elegy | elegy/hooks.py | [
"Apache-2.0"
] | Python | add_summary | None | def add_summary(name: tp.Optional[str], value: np.ndarray) -> None:
"""
A hook that lets you define a summary in the current module. Its primary
use is to keep track of certain values as they flow through the network
so `Model.summary()` can show a representation of architecture.
```python
def ... |
A hook that lets you define a summary in the current module. Its primary
use is to keep track of certain values as they flow through the network
so `Model.summary()` can show a representation of architecture.
```python
def call(self, x):
...
y = jax.nn.relu(x)
elegy.add_sum... | A hook that lets you define a summary in the current module. Its primary
use is to keep track of certain values as they flow through the network
so `Model.summary()` can show a representation of architecture.
| [
"A",
"hook",
"that",
"lets",
"you",
"define",
"a",
"summary",
"in",
"the",
"current",
"module",
".",
"Its",
"primary",
"use",
"is",
"to",
"keep",
"track",
"of",
"certain",
"values",
"as",
"they",
"flow",
"through",
"the",
"network",
"so",
"`",
"Model",
... | def add_summary(name: tp.Optional[str], value: np.ndarray) -> None:
if LOCAL.contexts:
context: Context = LOCAL.contexts[-1]
module = context.module_c[-1]
if not context.get_summaries:
return
base_name = "/".join(context.path_names_c)
base_name = f"{base_name}/{na... | [
"def",
"add_summary",
"(",
"name",
":",
"tp",
".",
"Optional",
"[",
"str",
"]",
",",
"value",
":",
"np",
".",
"ndarray",
")",
"->",
"None",
":",
"if",
"LOCAL",
".",
"contexts",
":",
"context",
":",
"Context",
"=",
"LOCAL",
".",
"contexts",
"[",
"-"... | A hook that lets you define a summary in the current module. | [
"A",
"hook",
"that",
"lets",
"you",
"define",
"a",
"summary",
"in",
"the",
"current",
"module",
"."
] | [
"\"\"\"\n A hook that lets you define a summary in the current module. Its primary\n use is to keep track of certain values as they flow through the network\n so `Model.summary()` can show a representation of architecture.\n\n ```python\n def call(self, x):\n ...\n y = jax.nn.relu(x)\n ... | [
{
"param": "name",
"type": "tp.Optional[str]"
},
{
"param": "value",
"type": "np.ndarray"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "name",
"type": "tp.Optional[str]",
"docstring": "The name of the loss. If a summary with the same\n`name` already exists a unique identifier will be generated.",
"docstring_tokens": [
"The",
"name",
"of... |
a4c358be0a80fcb8868a2d25663cac65bf87a828 | abhinavsp0730/elegy | elegy/hooks.py | [
"Apache-2.0"
] | Python | next_rng_key | PRNGKey | def next_rng_key() -> PRNGKey:
"""
A hook that returns a unique JAX RNG key split from the current global key.
```python
key = elegy.next_rng_key()
x = jax.random.uniform(key, [])
```
Returns:
A unique (within a transformed function) JAX rng key that can be used with
APIs s... |
A hook that returns a unique JAX RNG key split from the current global key.
```python
key = elegy.next_rng_key()
x = jax.random.uniform(key, [])
```
Returns:
A unique (within a transformed function) JAX rng key that can be used with
APIs such as ``jax.random.uniform``.
| A hook that returns a unique JAX RNG key split from the current global key. | [
"A",
"hook",
"that",
"returns",
"a",
"unique",
"JAX",
"RNG",
"key",
"split",
"from",
"the",
"current",
"global",
"key",
"."
] | def next_rng_key() -> PRNGKey:
if LOCAL.contexts:
context: Context = LOCAL.contexts[-1]
if context.rng_sequence is not None:
context: Context = LOCAL.contexts[-1]
return next(context.rng_sequence)
else:
raise ValueError(
"Cannot execute `rn... | [
"def",
"next_rng_key",
"(",
")",
"->",
"PRNGKey",
":",
"if",
"LOCAL",
".",
"contexts",
":",
"context",
":",
"Context",
"=",
"LOCAL",
".",
"contexts",
"[",
"-",
"1",
"]",
"if",
"context",
".",
"rng_sequence",
"is",
"not",
"None",
":",
"context",
":",
... | A hook that returns a unique JAX RNG key split from the current global key. | [
"A",
"hook",
"that",
"returns",
"a",
"unique",
"JAX",
"RNG",
"key",
"split",
"from",
"the",
"current",
"global",
"key",
"."
] | [
"\"\"\"\n A hook that returns a unique JAX RNG key split from the current global key.\n\n ```python\n key = elegy.next_rng_key()\n x = jax.random.uniform(key, [])\n ```\n\n Returns:\n A unique (within a transformed function) JAX rng key that can be used with\n APIs such as ``jax.rand... | [] | {
"returns": [
{
"docstring": "A unique (within a transformed function) JAX rng key that can be used with\nAPIs such as ``jax.random.uniform``.",
"docstring_tokens": [
"A",
"unique",
"(",
"within",
"a",
"transformed",
"function",
")",
... |
4e0f85a07f8336a7f734193fec894853b1037a68 | abhinavsp0730/elegy | elegy/losses/sparse_categorical_crossentropy.py | [
"Apache-2.0"
] | Python | call | jnp.ndarray | def call(
self, y_true, y_pred, sample_weight: tp.Optional[jnp.ndarray] = None
) -> jnp.ndarray:
"""
Invokes the `SparseCategoricalCrossentropy` instance.
Arguments:
y_true: Ground truth values.
y_pred: The predicted values.
sample_weight: Acts as... |
Invokes the `SparseCategoricalCrossentropy` instance.
Arguments:
y_true: Ground truth values.
y_pred: The predicted values.
sample_weight: Acts as a
coefficient for the loss. If a scalar is provided, then the loss is
simply scaled by ... | Invokes the `SparseCategoricalCrossentropy` instance. | [
"Invokes",
"the",
"`",
"SparseCategoricalCrossentropy",
"`",
"instance",
"."
] | def call(
self, y_true, y_pred, sample_weight: tp.Optional[jnp.ndarray] = None
) -> jnp.ndarray:
return sparse_categorical_crossentropy(
y_true, y_pred, from_logits=self._from_logits
) | [
"def",
"call",
"(",
"self",
",",
"y_true",
",",
"y_pred",
",",
"sample_weight",
":",
"tp",
".",
"Optional",
"[",
"jnp",
".",
"ndarray",
"]",
"=",
"None",
")",
"->",
"jnp",
".",
"ndarray",
":",
"return",
"sparse_categorical_crossentropy",
"(",
"y_true",
"... | Invokes the `SparseCategoricalCrossentropy` instance. | [
"Invokes",
"the",
"`",
"SparseCategoricalCrossentropy",
"`",
"instance",
"."
] | [
"\"\"\"\n Invokes the `SparseCategoricalCrossentropy` instance.\n\n Arguments:\n y_true: Ground truth values.\n y_pred: The predicted values.\n sample_weight: Acts as a\n coefficient for the loss. If a scalar is provided, then the loss is\n ... | [
{
"param": "self",
"type": null
},
{
"param": "y_true",
"type": null
},
{
"param": "y_pred",
"type": null
},
{
"param": "sample_weight",
"type": "tp.Optional[jnp.ndarray]"
}
] | {
"returns": [
{
"docstring": "Loss values per sample.",
"docstring_tokens": [
"Loss",
"values",
"per",
"sample",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": nu... |
dcdcccf2d24b2128970a5eabb0c9966cf6fcaced | abhinavsp0730/elegy | elegy/losses/mean_absolute_percentage_error.py | [
"Apache-2.0"
] | Python | mean_percentage_absolute_error | jnp.ndarray | def mean_percentage_absolute_error(
y_true: jnp.ndarray, y_pred: jnp.ndarray
) -> jnp.ndarray:
"""
Computes the mean absolute percentage error (MAPE) between labels and predictions.
After computing the absolute distance between the true value and the prediction value
and divide by the true value, t... |
Computes the mean absolute percentage error (MAPE) between labels and predictions.
After computing the absolute distance between the true value and the prediction value
and divide by the true value, the mean value over the last dimension is returned.
Usage:
```python
rng = jax.random.PRNGKey... | Computes the mean absolute percentage error (MAPE) between labels and predictions.
After computing the absolute distance between the true value and the prediction value
and divide by the true value, the mean value over the last dimension is returned.
| [
"Computes",
"the",
"mean",
"absolute",
"percentage",
"error",
"(",
"MAPE",
")",
"between",
"labels",
"and",
"predictions",
".",
"After",
"computing",
"the",
"absolute",
"distance",
"between",
"the",
"true",
"value",
"and",
"the",
"prediction",
"value",
"and",
... | def mean_percentage_absolute_error(
y_true: jnp.ndarray, y_pred: jnp.ndarray
) -> jnp.ndarray:
y_true = y_true.astype(y_pred.dtype)
diff = jnp.abs((y_pred - y_true) / jnp.maximum(jnp.abs(y_true), utils.EPSILON))
return 100.0 * jnp.mean(diff, axis=-1) | [
"def",
"mean_percentage_absolute_error",
"(",
"y_true",
":",
"jnp",
".",
"ndarray",
",",
"y_pred",
":",
"jnp",
".",
"ndarray",
")",
"->",
"jnp",
".",
"ndarray",
":",
"y_true",
"=",
"y_true",
".",
"astype",
"(",
"y_pred",
".",
"dtype",
")",
"diff",
"=",
... | Computes the mean absolute percentage error (MAPE) between labels and predictions. | [
"Computes",
"the",
"mean",
"absolute",
"percentage",
"error",
"(",
"MAPE",
")",
"between",
"labels",
"and",
"predictions",
"."
] | [
"\"\"\"\n Computes the mean absolute percentage error (MAPE) between labels and predictions.\n\n After computing the absolute distance between the true value and the prediction value\n and divide by the true value, the mean value over the last dimension is returned.\n\n Usage:\n\n ```python\n rng ... | [
{
"param": "y_true",
"type": "jnp.ndarray"
},
{
"param": "y_pred",
"type": "jnp.ndarray"
}
] | {
"returns": [
{
"docstring": "Mean absolute percentage error values. shape = `[batch_size, d0, ..",
"docstring_tokens": [
"Mean",
"absolute",
"percentage",
"error",
"values",
".",
"shape",
"=",
"`",
"[",
"batch_si... |
dcdcccf2d24b2128970a5eabb0c9966cf6fcaced | abhinavsp0730/elegy | elegy/losses/mean_absolute_percentage_error.py | [
"Apache-2.0"
] | Python | call | jnp.ndarray | def call(
self,
y_true: jnp.ndarray,
y_pred: jnp.ndarray,
sample_weight: tp.Optional[
jnp.ndarray
] = None, # not used, __call__ handles it, left for documentation purposes.
) -> jnp.ndarray:
"""
Invokes the `MeanAbsolutePercentageError` instance.... |
Invokes the `MeanAbsolutePercentageError` instance.
Arguments:
y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except
sparse loss functions such as sparse categorical crossentropy where
shape = `[batch_size, d0, .. dN-1]`
y_pred: ... | Invokes the `MeanAbsolutePercentageError` instance. | [
"Invokes",
"the",
"`",
"MeanAbsolutePercentageError",
"`",
"instance",
"."
] | def call(
self,
y_true: jnp.ndarray,
y_pred: jnp.ndarray,
sample_weight: tp.Optional[
jnp.ndarray
] = None,
) -> jnp.ndarray:
return mean_percentage_absolute_error(y_true, y_pred) | [
"def",
"call",
"(",
"self",
",",
"y_true",
":",
"jnp",
".",
"ndarray",
",",
"y_pred",
":",
"jnp",
".",
"ndarray",
",",
"sample_weight",
":",
"tp",
".",
"Optional",
"[",
"jnp",
".",
"ndarray",
"]",
"=",
"None",
",",
")",
"->",
"jnp",
".",
"ndarray",... | Invokes the `MeanAbsolutePercentageError` instance. | [
"Invokes",
"the",
"`",
"MeanAbsolutePercentageError",
"`",
"instance",
"."
] | [
"# not used, __call__ handles it, left for documentation purposes.",
"\"\"\"\n Invokes the `MeanAbsolutePercentageError` instance.\n\n Arguments:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except\n sparse loss functions such as sparse categorical cros... | [
{
"param": "self",
"type": null
},
{
"param": "y_true",
"type": "jnp.ndarray"
},
{
"param": "y_pred",
"type": "jnp.ndarray"
},
{
"param": "sample_weight",
"type": "tp.Optional[\n jnp.ndarray\n ]"
}
] | {
"returns": [
{
"docstring": "Weighted loss float `Tensor`. If `reduction` is `NONE`, this has\nshape `[batch_size, d0, .. dN-1]`; otherwise, it is scalar. (Note `dN-1`\nbecause all loss functions reduce by 1 dimension, usually axis=-1.)",
"docstring_tokens": [
"Weighted",
"loss",
... |
f7a5ec8da870c9306c41484d96377460b3cdcd98 | abhinavsp0730/elegy | elegy/metrics/reduce_confusion_matrix.py | [
"Apache-2.0"
] | Python | call | jnp.ndarray | def call(
self,
y_true: jnp.ndarray,
y_pred: jnp.ndarray,
sample_weight: tp.Optional[jnp.ndarray] = None,
) -> jnp.ndarray:
"""
Accumulates confusion matrix metrics for computing the reduction metric.
Arguments:
y_true: Ground truth values. shape ... |
Accumulates confusion matrix metrics for computing the reduction metric.
Arguments:
y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.
sample_weight: Optional weighting of each example. ... | Accumulates confusion matrix metrics for computing the reduction metric. | [
"Accumulates",
"confusion",
"matrix",
"metrics",
"for",
"computing",
"the",
"reduction",
"metric",
"."
] | def call(
self,
y_true: jnp.ndarray,
y_pred: jnp.ndarray,
sample_weight: tp.Optional[jnp.ndarray] = None,
) -> jnp.ndarray:
cm_metric = hooks.get_state(
"cm_metric",
shape=[],
dtype=jnp.int32,
initializer=initializers.Constant(0... | [
"def",
"call",
"(",
"self",
",",
"y_true",
":",
"jnp",
".",
"ndarray",
",",
"y_pred",
":",
"jnp",
".",
"ndarray",
",",
"sample_weight",
":",
"tp",
".",
"Optional",
"[",
"jnp",
".",
"ndarray",
"]",
"=",
"None",
",",
")",
"->",
"jnp",
".",
"ndarray",... | Accumulates confusion matrix metrics for computing the reduction metric. | [
"Accumulates",
"confusion",
"matrix",
"metrics",
"for",
"computing",
"the",
"reduction",
"metric",
"."
] | [
"\"\"\"\n Accumulates confusion matrix metrics for computing the reduction metric.\n\n Arguments:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n sample_weight: Optional weightin... | [
{
"param": "self",
"type": null
},
{
"param": "y_true",
"type": "jnp.ndarray"
},
{
"param": "y_pred",
"type": "jnp.ndarray"
},
{
"param": "sample_weight",
"type": "tp.Optional[jnp.ndarray]"
}
] | {
"returns": [
{
"docstring": "Array with the cummulative reduce metric.",
"docstring_tokens": [
"Array",
"with",
"the",
"cummulative",
"reduce",
"metric",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"iden... |
d4794bc6cc433b7eff94a13d8ec5614d39c16fbc | abhinavsp0730/elegy | elegy/module.py | [
"Apache-2.0"
] | Python | apply | "ApplyCallable" | def apply(
self,
parameters: tp.Optional[tp.Dict] = None,
states: tp.Optional[tp.Dict] = None,
rng: tp.Optional[tp.Union[np.ndarray, int]] = None,
get_summaries: bool = False,
training: bool = True,
) -> "ApplyCallable":
"""
Applies your function injec... |
Applies your function injecting some context arguments.
Arguments:
parameters:
states:
rng:
get_summaries:
Returns:
A function with the same signature as `call` that will
execute the computation given the context argument... | Applies your function injecting some context arguments. | [
"Applies",
"your",
"function",
"injecting",
"some",
"context",
"arguments",
"."
] | def apply(
self,
parameters: tp.Optional[tp.Dict] = None,
states: tp.Optional[tp.Dict] = None,
rng: tp.Optional[tp.Union[np.ndarray, int]] = None,
get_summaries: bool = False,
training: bool = True,
) -> "ApplyCallable":
@utils.wraps(self.call)
def app... | [
"def",
"apply",
"(",
"self",
",",
"parameters",
":",
"tp",
".",
"Optional",
"[",
"tp",
".",
"Dict",
"]",
"=",
"None",
",",
"states",
":",
"tp",
".",
"Optional",
"[",
"tp",
".",
"Dict",
"]",
"=",
"None",
",",
"rng",
":",
"tp",
".",
"Optional",
"... | Applies your function injecting some context arguments. | [
"Applies",
"your",
"function",
"injecting",
"some",
"context",
"arguments",
"."
] | [
"\"\"\"\n Applies your function injecting some context arguments.\n\n Arguments:\n parameters:\n states:\n rng:\n get_summaries:\n\n Returns:\n A function with the same signature as `call` that will\n execute the computation give... | [
{
"param": "self",
"type": null
},
{
"param": "parameters",
"type": "tp.Optional[tp.Dict]"
},
{
"param": "states",
"type": "tp.Optional[tp.Dict]"
},
{
"param": "rng",
"type": "tp.Optional[tp.Union[np.ndarray, int]]"
},
{
"param": "get_summaries",
"type": "bool... | {
"returns": [
{
"docstring": "A function with the same signature as `call` that will\nexecute the computation given the context arguments\npassed to `apply`.",
"docstring_tokens": [
"A",
"function",
"with",
"the",
"same",
"signature",
"as",
... |
ab33bda30c7f847c4fa7b1b465cc0ec41311ebd0 | extremscorner/mdfourier-dac | mdfourier-dac.py | [
"Unlicense"
] | Python | fullprint | null | def fullprint(*args, **kwargs):
"""Print an ndarray without truncation.
Use when troubleshooting signal generation
Via https://stackoverflow.com/a/24542498/2738262"""
from pprint import pprint
opt = np.get_printoptions()
np.set_printoptions(threshold=np.inf)
pprint(*args, **kwargs)
np.set_prin... | Print an ndarray without truncation.
Use when troubleshooting signal generation
Via https://stackoverflow.com/a/24542498/2738262 | Print an ndarray without truncation.
Use when troubleshooting signal generation
| [
"Print",
"an",
"ndarray",
"without",
"truncation",
".",
"Use",
"when",
"troubleshooting",
"signal",
"generation"
] | def fullprint(*args, **kwargs):
from pprint import pprint
opt = np.get_printoptions()
np.set_printoptions(threshold=np.inf)
pprint(*args, **kwargs)
np.set_printoptions(**opt) | [
"def",
"fullprint",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"from",
"pprint",
"import",
"pprint",
"opt",
"=",
"np",
".",
"get_printoptions",
"(",
")",
"np",
".",
"set_printoptions",
"(",
"threshold",
"=",
"np",
".",
"inf",
")",
"pprint",
"(",
... | Print an ndarray without truncation. | [
"Print",
"an",
"ndarray",
"without",
"truncation",
"."
] | [
"\"\"\"Print an ndarray without truncation.\n\nUse when troubleshooting signal generation\n\nVia https://stackoverflow.com/a/24542498/2738262\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
ab33bda30c7f847c4fa7b1b465cc0ec41311ebd0 | extremscorner/mdfourier-dac | mdfourier-dac.py | [
"Unlicense"
] | Python | nonbl_saw_sweep | <not_specific> | def nonbl_saw_sweep(rate):
"""Generate a non-bandlimited saw sweep."""
baseafreq = 20.0 / rate
noctaves = int((1/baseafreq) // 1).bit_length() - 2
out = []
lastendphase = 0
for octave in range(noctaves):
afreq = np.geomspace(baseafreq, baseafreq * 2,
num=rate... | Generate a non-bandlimited saw sweep. | Generate a non-bandlimited saw sweep. | [
"Generate",
"a",
"non",
"-",
"bandlimited",
"saw",
"sweep",
"."
] | def nonbl_saw_sweep(rate):
baseafreq = 20.0 / rate
noctaves = int((1/baseafreq) // 1).bit_length() - 2
out = []
lastendphase = 0
for octave in range(noctaves):
afreq = np.geomspace(baseafreq, baseafreq * 2,
num=rate * 2, endpoint=False)
phase = np.cumsum(... | [
"def",
"nonbl_saw_sweep",
"(",
"rate",
")",
":",
"baseafreq",
"=",
"20.0",
"/",
"rate",
"noctaves",
"=",
"int",
"(",
"(",
"1",
"/",
"baseafreq",
")",
"//",
"1",
")",
".",
"bit_length",
"(",
")",
"-",
"2",
"out",
"=",
"[",
"]",
"lastendphase",
"=",
... | Generate a non-bandlimited saw sweep. | [
"Generate",
"a",
"non",
"-",
"bandlimited",
"saw",
"sweep",
"."
] | [
"\"\"\"Generate a non-bandlimited saw sweep.\"\"\""
] | [
{
"param": "rate",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "rate",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2a6dd12fe1983a1b5f53e4fe5bda3cbdfd058734 | sdw95927/InstanceSegmentation-CycleGAN | segmentation_functions.py | [
"MIT"
] | Python | convert_to_optical_densities | <not_specific> | def convert_to_optical_densities(img_RGB, r0=255, g0=255, b0=255):
"""Conver RGB image to optical densities with same shape as input image."""
OD = img_RGB.astype(float)
OD[:,:,0] /= r0
OD[:,:,1] /= g0
OD[:,:,2] /= b0
return -np.log(OD+0.00001) | Conver RGB image to optical densities with same shape as input image. | Conver RGB image to optical densities with same shape as input image. | [
"Conver",
"RGB",
"image",
"to",
"optical",
"densities",
"with",
"same",
"shape",
"as",
"input",
"image",
"."
] | def convert_to_optical_densities(img_RGB, r0=255, g0=255, b0=255):
OD = img_RGB.astype(float)
OD[:,:,0] /= r0
OD[:,:,1] /= g0
OD[:,:,2] /= b0
return -np.log(OD+0.00001) | [
"def",
"convert_to_optical_densities",
"(",
"img_RGB",
",",
"r0",
"=",
"255",
",",
"g0",
"=",
"255",
",",
"b0",
"=",
"255",
")",
":",
"OD",
"=",
"img_RGB",
".",
"astype",
"(",
"float",
")",
"OD",
"[",
":",
",",
":",
",",
"0",
"]",
"/=",
"r0",
"... | Conver RGB image to optical densities with same shape as input image. | [
"Conver",
"RGB",
"image",
"to",
"optical",
"densities",
"with",
"same",
"shape",
"as",
"input",
"image",
"."
] | [
"\"\"\"Conver RGB image to optical densities with same shape as input image.\"\"\""
] | [
{
"param": "img_RGB",
"type": null
},
{
"param": "r0",
"type": null
},
{
"param": "g0",
"type": null
},
{
"param": "b0",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "img_RGB",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "r0",
"type": null,
"docstring": null,
"docstring_tokens": ... |
2a6dd12fe1983a1b5f53e4fe5bda3cbdfd058734 | sdw95927/InstanceSegmentation-CycleGAN | segmentation_functions.py | [
"MIT"
] | Python | channel_deconvolution | <not_specific> | def channel_deconvolution (img_RGB, staining_type, plot_image=False, to_normalize=True):
"""Deconvolute RGB image into different staining channels.
Ref: https://blog.bham.ac.uk/intellimic/g-landini-software/colour-deconvolution/
Args:
img_RGB: A uint8 numpy array with RGB channels.
s... | Deconvolute RGB image into different staining channels.
Ref: https://blog.bham.ac.uk/intellimic/g-landini-software/colour-deconvolution/
Args:
img_RGB: A uint8 numpy array with RGB channels.
staining_type: Dyes used to stain the image; choose one from ("HDB", "HRB", "HDR", "HEB").
... | Deconvolute RGB image into different staining channels. | [
"Deconvolute",
"RGB",
"image",
"into",
"different",
"staining",
"channels",
"."
] | def channel_deconvolution (img_RGB, staining_type, plot_image=False, to_normalize=True):
if staining_type == "HDB":
channels = ("Hematoxylin", "DAB", "Background")
stain_OD = np.asarray([[0.650,0.704,0.286],[0.268,0.570,0.776],[0.754,0.077,0.652]])
elif staining_type == "HRB":
channels =... | [
"def",
"channel_deconvolution",
"(",
"img_RGB",
",",
"staining_type",
",",
"plot_image",
"=",
"False",
",",
"to_normalize",
"=",
"True",
")",
":",
"if",
"staining_type",
"==",
"\"HDB\"",
":",
"channels",
"=",
"(",
"\"Hematoxylin\"",
",",
"\"DAB\"",
",",
"\"Bac... | Deconvolute RGB image into different staining channels. | [
"Deconvolute",
"RGB",
"image",
"into",
"different",
"staining",
"channels",
"."
] | [
"\"\"\"Deconvolute RGB image into different staining channels.\n Ref: https://blog.bham.ac.uk/intellimic/g-landini-software/colour-deconvolution/\n \n Args:\n img_RGB: A uint8 numpy array with RGB channels.\n staining_type: Dyes used to stain the image; choose one from (\"HDB\", \"HRB\", \... | [
{
"param": "img_RGB",
"type": null
},
{
"param": "staining_type",
"type": null
},
{
"param": "plot_image",
"type": null
},
{
"param": "to_normalize",
"type": null
}
] | {
"returns": [
{
"docstring": "An unnormlized h*w*3 deconvoluted matrix and 3 different channels normalized to [0, 1] seperately.",
"docstring_tokens": [
"An",
"unnormlized",
"h",
"*",
"w",
"*",
"3",
"deconvoluted",
"matrix",
... |
2a6dd12fe1983a1b5f53e4fe5bda3cbdfd058734 | sdw95927/InstanceSegmentation-CycleGAN | segmentation_functions.py | [
"MIT"
] | Python | make_8UC | <not_specific> | def make_8UC(mat, normalized=True):
"""Convert the matrix to the equivalent matrix of the unsigned 8 bit integer datatype."""
if normalized:
mat_uint8 = np.array(mat.copy()*255, dtype=np.uint8)
else:
mat_uint8 = np.array(normalize(mat)*255, dtype=np.uint8)
return mat_uint8 | Convert the matrix to the equivalent matrix of the unsigned 8 bit integer datatype. | Convert the matrix to the equivalent matrix of the unsigned 8 bit integer datatype. | [
"Convert",
"the",
"matrix",
"to",
"the",
"equivalent",
"matrix",
"of",
"the",
"unsigned",
"8",
"bit",
"integer",
"datatype",
"."
] | def make_8UC(mat, normalized=True):
if normalized:
mat_uint8 = np.array(mat.copy()*255, dtype=np.uint8)
else:
mat_uint8 = np.array(normalize(mat)*255, dtype=np.uint8)
return mat_uint8 | [
"def",
"make_8UC",
"(",
"mat",
",",
"normalized",
"=",
"True",
")",
":",
"if",
"normalized",
":",
"mat_uint8",
"=",
"np",
".",
"array",
"(",
"mat",
".",
"copy",
"(",
")",
"*",
"255",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"else",
":",
"mat_u... | Convert the matrix to the equivalent matrix of the unsigned 8 bit integer datatype. | [
"Convert",
"the",
"matrix",
"to",
"the",
"equivalent",
"matrix",
"of",
"the",
"unsigned",
"8",
"bit",
"integer",
"datatype",
"."
] | [
"\"\"\"Convert the matrix to the equivalent matrix of the unsigned 8 bit integer datatype.\"\"\""
] | [
{
"param": "mat",
"type": null
},
{
"param": "normalized",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "mat",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "normalized",
"type": null,
"docstring": null,
"docstring_token... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.