repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
nwilming/ocupy | ocupy/simulator.py | makeHist | def makeHist(x_val, y_val, fit=spline_base.fit2d,
bins=[np.linspace(-36.5,36.5,74),np.linspace(-180,180,361)]):
"""
Constructs a (fitted) histogram of the given data.
Parameters:
x_val : array
The data to be histogrammed along the x-axis.
y_val : array
... | python | def makeHist(x_val, y_val, fit=spline_base.fit2d,
bins=[np.linspace(-36.5,36.5,74),np.linspace(-180,180,361)]):
"""
Constructs a (fitted) histogram of the given data.
Parameters:
x_val : array
The data to be histogrammed along the x-axis.
y_val : array
... | [
"def",
"makeHist",
"(",
"x_val",
",",
"y_val",
",",
"fit",
"=",
"spline_base",
".",
"fit2d",
",",
"bins",
"=",
"[",
"np",
".",
"linspace",
"(",
"-",
"36.5",
",",
"36.5",
",",
"74",
")",
",",
"np",
".",
"linspace",
"(",
"-",
"180",
",",
"180",
"... | Constructs a (fitted) histogram of the given data.
Parameters:
x_val : array
The data to be histogrammed along the x-axis.
y_val : array
The data to be histogrammed along the y-axis.
fit : function or None, optional
The function to use in order to fi... | [
"Constructs",
"a",
"(",
"fitted",
")",
"histogram",
"of",
"the",
"given",
"data",
".",
"Parameters",
":",
"x_val",
":",
"array",
"The",
"data",
"to",
"be",
"histogrammed",
"along",
"the",
"x",
"-",
"axis",
".",
"y_val",
":",
"array",
"The",
"data",
"to... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L374-L405 |
nwilming/ocupy | ocupy/simulator.py | firstSacDist | def firstSacDist(fm):
"""
Computes the distribution of angle and length
combinations that were made as first saccades
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed
"""
ang, leng, ad, ld = anglendiff(fm, return_abs=True)
... | python | def firstSacDist(fm):
"""
Computes the distribution of angle and length
combinations that were made as first saccades
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed
"""
ang, leng, ad, ld = anglendiff(fm, return_abs=True)
... | [
"def",
"firstSacDist",
"(",
"fm",
")",
":",
"ang",
",",
"leng",
",",
"ad",
",",
"ld",
"=",
"anglendiff",
"(",
"fm",
",",
"return_abs",
"=",
"True",
")",
"y_arg",
"=",
"leng",
"[",
"0",
"]",
"[",
"np",
".",
"roll",
"(",
"fm",
".",
"fix",
"==",
... | Computes the distribution of angle and length
combinations that were made as first saccades
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed | [
"Computes",
"the",
"distribution",
"of",
"angle",
"and",
"length",
"combinations",
"that",
"were",
"made",
"as",
"first",
"saccades",
"Parameters",
":",
"fm",
":",
"ocupy",
".",
"fixmat",
"The",
"fixation",
"data",
"to",
"be",
"analysed"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L509-L523 |
nwilming/ocupy | ocupy/simulator.py | trajLenDist | def trajLenDist(fm):
"""
Computes the distribution of trajectory lengths, i.e.
the number of saccades that were made as a part of one trajectory
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed
"""
trajLen = np.roll(fm.fix, 1... | python | def trajLenDist(fm):
"""
Computes the distribution of trajectory lengths, i.e.
the number of saccades that were made as a part of one trajectory
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed
"""
trajLen = np.roll(fm.fix, 1... | [
"def",
"trajLenDist",
"(",
"fm",
")",
":",
"trajLen",
"=",
"np",
".",
"roll",
"(",
"fm",
".",
"fix",
",",
"1",
")",
"[",
"fm",
".",
"fix",
"==",
"min",
"(",
"fm",
".",
"fix",
")",
"]",
"val",
",",
"borders",
"=",
"np",
".",
"histogram",
"(",
... | Computes the distribution of trajectory lengths, i.e.
the number of saccades that were made as a part of one trajectory
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed | [
"Computes",
"the",
"distribution",
"of",
"trajectory",
"lengths",
"i",
".",
"e",
".",
"the",
"number",
"of",
"saccades",
"that",
"were",
"made",
"as",
"a",
"part",
"of",
"one",
"trajectory",
"Parameters",
":",
"fm",
":",
"ocupy",
".",
"fixmat",
"The",
"f... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L525-L539 |
nwilming/ocupy | ocupy/simulator.py | reshift | def reshift(I):
"""
Transforms the given number element into a range of [-180, 180],
which covers all possible angle differences. This method reshifts larger or
smaller numbers that might be the output of other angular calculations
into that range by adding or subtracting 360, respectively.
To... | python | def reshift(I):
"""
Transforms the given number element into a range of [-180, 180],
which covers all possible angle differences. This method reshifts larger or
smaller numbers that might be the output of other angular calculations
into that range by adding or subtracting 360, respectively.
To... | [
"def",
"reshift",
"(",
"I",
")",
":",
"# Output -180 to +180",
"if",
"type",
"(",
"I",
")",
"==",
"list",
":",
"I",
"=",
"np",
".",
"array",
"(",
"I",
")",
"return",
"(",
"(",
"I",
"-",
"180",
")",
"%",
"360",
")",
"-",
"180"
] | Transforms the given number element into a range of [-180, 180],
which covers all possible angle differences. This method reshifts larger or
smaller numbers that might be the output of other angular calculations
into that range by adding or subtracting 360, respectively.
To make sure that angular data... | [
"Transforms",
"the",
"given",
"number",
"element",
"into",
"a",
"range",
"of",
"[",
"-",
"180",
"180",
"]",
"which",
"covers",
"all",
"possible",
"angle",
"differences",
".",
"This",
"method",
"reshifts",
"larger",
"or",
"smaller",
"numbers",
"that",
"might"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L541-L562 |
nwilming/ocupy | ocupy/simulator.py | FixGen.initializeData | def initializeData(self, fit = None, full_H1=None, max_length = 40,
in_deg = True):
"""
Prepares the data to be replicated. Calculates the second-order length
and angle dependencies between saccades and stores them in a fitted
histogram.
Parameters:
... | python | def initializeData(self, fit = None, full_H1=None, max_length = 40,
in_deg = True):
"""
Prepares the data to be replicated. Calculates the second-order length
and angle dependencies between saccades and stores them in a fitted
histogram.
Parameters:
... | [
"def",
"initializeData",
"(",
"self",
",",
"fit",
"=",
"None",
",",
"full_H1",
"=",
"None",
",",
"max_length",
"=",
"40",
",",
"in_deg",
"=",
"True",
")",
":",
"a",
",",
"l",
",",
"ad",
",",
"ld",
"=",
"anglendiff",
"(",
"self",
".",
"fm",
",",
... | Prepares the data to be replicated. Calculates the second-order length
and angle dependencies between saccades and stores them in a fitted
histogram.
Parameters:
fit : function, optional
The method to use for fitting the histogram
full_H1 : twod... | [
"Prepares",
"the",
"data",
"to",
"be",
"replicated",
".",
"Calculates",
"the",
"second",
"-",
"order",
"length",
"and",
"angle",
"dependencies",
"between",
"saccades",
"and",
"stores",
"them",
"in",
"a",
"fitted",
"histogram",
".",
"Parameters",
":",
"fit",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L90-L157 |
nwilming/ocupy | ocupy/simulator.py | FixGen._calc_xy | def _calc_xy(self, xxx_todo_changeme, angle, length):
"""
Calculates the coordinates after a specific saccade was made.
Parameters:
(x,y) : tuple of floats or ints
The coordinates before the saccade was made
angle : float or int
Th... | python | def _calc_xy(self, xxx_todo_changeme, angle, length):
"""
Calculates the coordinates after a specific saccade was made.
Parameters:
(x,y) : tuple of floats or ints
The coordinates before the saccade was made
angle : float or int
Th... | [
"def",
"_calc_xy",
"(",
"self",
",",
"xxx_todo_changeme",
",",
"angle",
",",
"length",
")",
":",
"(",
"x",
",",
"y",
")",
"=",
"xxx_todo_changeme",
"return",
"(",
"x",
"+",
"(",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
"*",
"length",
")",
","... | Calculates the coordinates after a specific saccade was made.
Parameters:
(x,y) : tuple of floats or ints
The coordinates before the saccade was made
angle : float or int
The angle that the next saccade encloses with the
horizonta... | [
"Calculates",
"the",
"coordinates",
"after",
"a",
"specific",
"saccade",
"was",
"made",
".",
"Parameters",
":",
"(",
"x",
"y",
")",
":",
"tuple",
"of",
"floats",
"or",
"ints",
"The",
"coordinates",
"before",
"the",
"saccade",
"was",
"made",
"angle",
":",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L159-L174 |
nwilming/ocupy | ocupy/simulator.py | FixGen._draw | def _draw(self, prev_angle = None, prev_length = None):
"""
Draws a new length- and angle-difference pair and calculates
length and angle absolutes matching the last saccade drawn.
Parameters:
prev_angle : float, optional
The last angle that was drawn in the ... | python | def _draw(self, prev_angle = None, prev_length = None):
"""
Draws a new length- and angle-difference pair and calculates
length and angle absolutes matching the last saccade drawn.
Parameters:
prev_angle : float, optional
The last angle that was drawn in the ... | [
"def",
"_draw",
"(",
"self",
",",
"prev_angle",
"=",
"None",
",",
"prev_length",
"=",
"None",
")",
":",
"if",
"(",
"prev_angle",
"is",
"None",
")",
"or",
"(",
"prev_length",
"is",
"None",
")",
":",
"(",
"length",
",",
"angle",
")",
"=",
"np",
".",
... | Draws a new length- and angle-difference pair and calculates
length and angle absolutes matching the last saccade drawn.
Parameters:
prev_angle : float, optional
The last angle that was drawn in the current trajectory
prev_length : float, optional
... | [
"Draws",
"a",
"new",
"length",
"-",
"and",
"angle",
"-",
"difference",
"pair",
"and",
"calculates",
"length",
"and",
"angle",
"absolutes",
"matching",
"the",
"last",
"saccade",
"drawn",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L176-L212 |
nwilming/ocupy | ocupy/simulator.py | FixGen.sample_many | def sample_many(self, num_samples = 2000):
"""
Generates a given number of trajectories, using the method sample().
Returns a fixmat with the generated data.
Parameters:
num_samples : int, optional
The number of trajectories that shall be generated.
... | python | def sample_many(self, num_samples = 2000):
"""
Generates a given number of trajectories, using the method sample().
Returns a fixmat with the generated data.
Parameters:
num_samples : int, optional
The number of trajectories that shall be generated.
... | [
"def",
"sample_many",
"(",
"self",
",",
"num_samples",
"=",
"2000",
")",
":",
"x",
"=",
"[",
"]",
"y",
"=",
"[",
"]",
"fix",
"=",
"[",
"]",
"sample",
"=",
"[",
"]",
"# XXX: Delete ProgressBar",
"pbar",
"=",
"ProgressBar",
"(",
"widgets",
"=",
"[",
... | Generates a given number of trajectories, using the method sample().
Returns a fixmat with the generated data.
Parameters:
num_samples : int, optional
The number of trajectories that shall be generated. | [
"Generates",
"a",
"given",
"number",
"of",
"trajectories",
"using",
"the",
"method",
"sample",
"()",
".",
"Returns",
"a",
"fixmat",
"with",
"the",
"generated",
"data",
".",
"Parameters",
":",
"num_samples",
":",
"int",
"optional",
"The",
"number",
"of",
"tra... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L241-L269 |
nwilming/ocupy | ocupy/simulator.py | FixGen.sample | def sample(self):
"""
Draws a trajectory length, first coordinates, lengths, angles and
length-angle-difference pairs according to the empirical distribution.
Each call creates one complete trajectory.
"""
lenghts = []
angles = []
coordinates = []
... | python | def sample(self):
"""
Draws a trajectory length, first coordinates, lengths, angles and
length-angle-difference pairs according to the empirical distribution.
Each call creates one complete trajectory.
"""
lenghts = []
angles = []
coordinates = []
... | [
"def",
"sample",
"(",
"self",
")",
":",
"lenghts",
"=",
"[",
"]",
"angles",
"=",
"[",
"]",
"coordinates",
"=",
"[",
"]",
"fix",
"=",
"[",
"]",
"sample_size",
"=",
"int",
"(",
"round",
"(",
"self",
".",
"trajLen_borders",
"[",
"self",
".",
"drawFrom... | Draws a trajectory length, first coordinates, lengths, angles and
length-angle-difference pairs according to the empirical distribution.
Each call creates one complete trajectory. | [
"Draws",
"a",
"trajectory",
"length",
"first",
"coordinates",
"lengths",
"angles",
"and",
"length",
"-",
"angle",
"-",
"difference",
"pairs",
"according",
"to",
"the",
"empirical",
"distribution",
".",
"Each",
"call",
"creates",
"one",
"complete",
"trajectory",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L271-L299 |
nwilming/ocupy | ocupy/simulator.py | FixGen.drawFrom | def drawFrom(self, cumsum, r):
"""
Draws a value from a cumulative sum.
Parameters:
cumsum : array
Cumulative sum from which shall be drawn.
Returns:
int : Index of the cumulative sum element drawn.
"""
a = cumsum.rsplit(... | python | def drawFrom(self, cumsum, r):
"""
Draws a value from a cumulative sum.
Parameters:
cumsum : array
Cumulative sum from which shall be drawn.
Returns:
int : Index of the cumulative sum element drawn.
"""
a = cumsum.rsplit(... | [
"def",
"drawFrom",
"(",
"self",
",",
"cumsum",
",",
"r",
")",
":",
"a",
"=",
"cumsum",
".",
"rsplit",
"(",
")",
"if",
"len",
"(",
"a",
")",
">",
"1",
":",
"b",
"=",
"eval",
"(",
"a",
"[",
"0",
"]",
")",
"[",
"int",
"(",
"a",
"[",
"1",
"... | Draws a value from a cumulative sum.
Parameters:
cumsum : array
Cumulative sum from which shall be drawn.
Returns:
int : Index of the cumulative sum element drawn. | [
"Draws",
"a",
"value",
"from",
"a",
"cumulative",
"sum",
".",
"Parameters",
":",
"cumsum",
":",
"array",
"Cumulative",
"sum",
"from",
"which",
"shall",
"be",
"drawn",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L305-L322 |
nwilming/ocupy | ocupy/fixmat.py | load | def load(path):
"""
Load fixmat at path.
Parameters:
path : string
Absolute path of the file to load from.
"""
f = h5py.File(path,'r')
if 'Fixmat' in f:
fm_group = f['Fixmat']
else:
fm_group = f['Datamat']
fields = {}
params = {}
for field, va... | python | def load(path):
"""
Load fixmat at path.
Parameters:
path : string
Absolute path of the file to load from.
"""
f = h5py.File(path,'r')
if 'Fixmat' in f:
fm_group = f['Fixmat']
else:
fm_group = f['Datamat']
fields = {}
params = {}
for field, va... | [
"def",
"load",
"(",
"path",
")",
":",
"f",
"=",
"h5py",
".",
"File",
"(",
"path",
",",
"'r'",
")",
"if",
"'Fixmat'",
"in",
"f",
":",
"fm_group",
"=",
"f",
"[",
"'Fixmat'",
"]",
"else",
":",
"fm_group",
"=",
"f",
"[",
"'Datamat'",
"]",
"fields",
... | Load fixmat at path.
Parameters:
path : string
Absolute path of the file to load from. | [
"Load",
"fixmat",
"at",
"path",
".",
"Parameters",
":",
"path",
":",
"string",
"Absolute",
"path",
"of",
"the",
"file",
"to",
"load",
"from",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L140-L160 |
nwilming/ocupy | ocupy/fixmat.py | compute_fdm | def compute_fdm(fixmat, fwhm=2, scale_factor=1):
"""
Computes a fixation density map for the calling fixmat.
Creates a map the size of the image fixations were recorded on.
Every pixel contains the frequency of fixations
for this image. The fixation map is smoothed by convolution with a
... | python | def compute_fdm(fixmat, fwhm=2, scale_factor=1):
"""
Computes a fixation density map for the calling fixmat.
Creates a map the size of the image fixations were recorded on.
Every pixel contains the frequency of fixations
for this image. The fixation map is smoothed by convolution with a
... | [
"def",
"compute_fdm",
"(",
"fixmat",
",",
"fwhm",
"=",
"2",
",",
"scale_factor",
"=",
"1",
")",
":",
"# image category must exist (>-1) and image_size must be non-empty",
"assert",
"(",
"len",
"(",
"fixmat",
".",
"image_size",
")",
"==",
"2",
"and",
"(",
"fixmat... | Computes a fixation density map for the calling fixmat.
Creates a map the size of the image fixations were recorded on.
Every pixel contains the frequency of fixations
for this image. The fixation map is smoothed by convolution with a
Gaussian kernel to approximate the area with highest processi... | [
"Computes",
"a",
"fixation",
"density",
"map",
"for",
"the",
"calling",
"fixmat",
".",
"Creates",
"a",
"map",
"the",
"size",
"of",
"the",
"image",
"fixations",
"were",
"recorded",
"on",
".",
"Every",
"pixel",
"contains",
"the",
"frequency",
"of",
"fixations"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L163-L207 |
nwilming/ocupy | ocupy/fixmat.py | relative_bias | def relative_bias(fm, scale_factor = 1, estimator = None):
"""
Computes the relative bias, i.e. the distribution of saccade angles
and amplitudes.
Parameters:
fm : DataMat
The fixation data to use
scale_factor : double
Returns:
2D probability distribution of s... | python | def relative_bias(fm, scale_factor = 1, estimator = None):
"""
Computes the relative bias, i.e. the distribution of saccade angles
and amplitudes.
Parameters:
fm : DataMat
The fixation data to use
scale_factor : double
Returns:
2D probability distribution of s... | [
"def",
"relative_bias",
"(",
"fm",
",",
"scale_factor",
"=",
"1",
",",
"estimator",
"=",
"None",
")",
":",
"assert",
"'fix'",
"in",
"fm",
".",
"fieldnames",
"(",
")",
",",
"\"Can not work without fixation numbers\"",
"excl",
"=",
"fm",
".",
"fix",
"-",
"n... | Computes the relative bias, i.e. the distribution of saccade angles
and amplitudes.
Parameters:
fm : DataMat
The fixation data to use
scale_factor : double
Returns:
2D probability distribution of saccade angles and amplitudes. | [
"Computes",
"the",
"relative",
"bias",
"i",
".",
"e",
".",
"the",
"distribution",
"of",
"saccade",
"angles",
"and",
"amplitudes",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L209-L249 |
nwilming/ocupy | ocupy/fixmat.py | DirectoryFixmatFactory | def DirectoryFixmatFactory(directory, categories = None, glob_str = '*.mat', var_name = 'fixmat'):
"""
Concatenates all fixmats in dir and returns the resulting single
fixmat.
Parameters:
directory : string
Path from which the fixmats should be loaded
categories : instan... | python | def DirectoryFixmatFactory(directory, categories = None, glob_str = '*.mat', var_name = 'fixmat'):
"""
Concatenates all fixmats in dir and returns the resulting single
fixmat.
Parameters:
directory : string
Path from which the fixmats should be loaded
categories : instan... | [
"def",
"DirectoryFixmatFactory",
"(",
"directory",
",",
"categories",
"=",
"None",
",",
"glob_str",
"=",
"'*.mat'",
",",
"var_name",
"=",
"'fixmat'",
")",
":",
"files",
"=",
"glob",
"(",
"join",
"(",
"directory",
",",
"glob_str",
")",
")",
"if",
"len",
"... | Concatenates all fixmats in dir and returns the resulting single
fixmat.
Parameters:
directory : string
Path from which the fixmats should be loaded
categories : instance of stimuli.Categories, optional
If given, the resulting fixmat provides direct access
... | [
"Concatenates",
"all",
"fixmats",
"in",
"dir",
"and",
"returns",
"the",
"resulting",
"single",
"fixmat",
".",
"Parameters",
":",
"directory",
":",
"string",
"Path",
"from",
"which",
"the",
"fixmats",
"should",
"be",
"loaded",
"categories",
":",
"instance",
"of... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L252-L280 |
nwilming/ocupy | ocupy/fixmat.py | FixmatFactory | def FixmatFactory(fixmatfile, categories = None, var_name = 'fixmat', field_name='x'):
"""
Loads a single fixmat (fixmatfile).
Parameters:
fixmatfile : string
The matlab fixmat that should be loaded.
categories : instance of stimuli.Categories, optional
Links dat... | python | def FixmatFactory(fixmatfile, categories = None, var_name = 'fixmat', field_name='x'):
"""
Loads a single fixmat (fixmatfile).
Parameters:
fixmatfile : string
The matlab fixmat that should be loaded.
categories : instance of stimuli.Categories, optional
Links dat... | [
"def",
"FixmatFactory",
"(",
"fixmatfile",
",",
"categories",
"=",
"None",
",",
"var_name",
"=",
"'fixmat'",
",",
"field_name",
"=",
"'x'",
")",
":",
"try",
":",
"data",
"=",
"loadmat",
"(",
"fixmatfile",
",",
"struct_as_record",
"=",
"False",
")",
"keys",... | Loads a single fixmat (fixmatfile).
Parameters:
fixmatfile : string
The matlab fixmat that should be loaded.
categories : instance of stimuli.Categories, optional
Links data in categories to data in fixmat. | [
"Loads",
"a",
"single",
"fixmat",
"(",
"fixmatfile",
")",
".",
"Parameters",
":",
"fixmatfile",
":",
"string",
"The",
"matlab",
"fixmat",
"that",
"should",
"be",
"loaded",
".",
"categories",
":",
"instance",
"of",
"stimuli",
".",
"Categories",
"optional",
"L... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L283-L325 |
nwilming/ocupy | ocupy/fixmat.py | FixMat.add_feature_values | def add_feature_values(self, features):
"""
Adds feature values of feature 'feature' to all fixations in
the calling fixmat.
For fixations out of the image boundaries, NaNs are returned.
The function generates a new attribute field named with the
string in featu... | python | def add_feature_values(self, features):
"""
Adds feature values of feature 'feature' to all fixations in
the calling fixmat.
For fixations out of the image boundaries, NaNs are returned.
The function generates a new attribute field named with the
string in featu... | [
"def",
"add_feature_values",
"(",
"self",
",",
"features",
")",
":",
"if",
"not",
"'x'",
"in",
"self",
".",
"fieldnames",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"\"\"add_feature_values expects to find\n (x,y) locations in self.x and self.y. But self.x does no... | Adds feature values of feature 'feature' to all fixations in
the calling fixmat.
For fixations out of the image boundaries, NaNs are returned.
The function generates a new attribute field named with the
string in features that contains an np.array listing feature
values... | [
"Adds",
"feature",
"values",
"of",
"feature",
"feature",
"to",
"all",
"fixations",
"in",
"the",
"calling",
"fixmat",
".",
"For",
"fixations",
"out",
"of",
"the",
"image",
"boundaries",
"NaNs",
"are",
"returned",
".",
"The",
"function",
"generates",
"a",
"new... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L19-L60 |
nwilming/ocupy | ocupy/fixmat.py | FixMat.make_reg_data | def make_reg_data(self, feature_list=None, all_controls=False):
"""
Generates two M x N matrices with M feature values at fixations for
N features. Controls are a random sample out of all non-fixated regions
of an image or fixations of the same subject group on a randomly chosen
... | python | def make_reg_data(self, feature_list=None, all_controls=False):
"""
Generates two M x N matrices with M feature values at fixations for
N features. Controls are a random sample out of all non-fixated regions
of an image or fixations of the same subject group on a randomly chosen
... | [
"def",
"make_reg_data",
"(",
"self",
",",
"feature_list",
"=",
"None",
",",
"all_controls",
"=",
"False",
")",
":",
"if",
"not",
"'x'",
"in",
"self",
".",
"fieldnames",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"\"\"make_reg_data expects to find\n (x... | Generates two M x N matrices with M feature values at fixations for
N features. Controls are a random sample out of all non-fixated regions
of an image or fixations of the same subject group on a randomly chosen
image. Fixations are pooled over all subjects in the calling fixmat.
... | [
"Generates",
"two",
"M",
"x",
"N",
"matrices",
"with",
"M",
"feature",
"values",
"at",
"fixations",
"for",
"N",
"features",
".",
"Controls",
"are",
"a",
"random",
"sample",
"out",
"of",
"all",
"non",
"-",
"fixated",
"regions",
"of",
"an",
"image",
"or",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L62-L138 |
nwilming/ocupy | ocupy/samples2fix.py | get_velocity | def get_velocity(samplemat, Hz, blinks=None):
'''
Compute velocity of eye-movements.
Samplemat must contain fields 'x' and 'y', specifying the x,y coordinates
of gaze location. The function assumes that the values in x,y are sampled
continously at a rate specified by 'Hz'.
'''
Hz = float(Hz... | python | def get_velocity(samplemat, Hz, blinks=None):
'''
Compute velocity of eye-movements.
Samplemat must contain fields 'x' and 'y', specifying the x,y coordinates
of gaze location. The function assumes that the values in x,y are sampled
continously at a rate specified by 'Hz'.
'''
Hz = float(Hz... | [
"def",
"get_velocity",
"(",
"samplemat",
",",
"Hz",
",",
"blinks",
"=",
"None",
")",
":",
"Hz",
"=",
"float",
"(",
"Hz",
")",
"distance",
"=",
"(",
"(",
"np",
".",
"diff",
"(",
"samplemat",
".",
"x",
")",
"**",
"2",
")",
"+",
"(",
"np",
".",
... | Compute velocity of eye-movements.
Samplemat must contain fields 'x' and 'y', specifying the x,y coordinates
of gaze location. The function assumes that the values in x,y are sampled
continously at a rate specified by 'Hz'. | [
"Compute",
"velocity",
"of",
"eye",
"-",
"movements",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/samples2fix.py#L11-L30 |
nwilming/ocupy | ocupy/samples2fix.py | saccade_detection | def saccade_detection(samplemat, Hz=200, threshold=30,
acc_thresh=2000, min_duration=21, min_movement=.35,
ignore_blinks=False):
'''
Detect saccades in a stream of gaze location samples.
Coordinates in samplemat are assumed to be in degrees.
Saccades are det... | python | def saccade_detection(samplemat, Hz=200, threshold=30,
acc_thresh=2000, min_duration=21, min_movement=.35,
ignore_blinks=False):
'''
Detect saccades in a stream of gaze location samples.
Coordinates in samplemat are assumed to be in degrees.
Saccades are det... | [
"def",
"saccade_detection",
"(",
"samplemat",
",",
"Hz",
"=",
"200",
",",
"threshold",
"=",
"30",
",",
"acc_thresh",
"=",
"2000",
",",
"min_duration",
"=",
"21",
",",
"min_movement",
"=",
".35",
",",
"ignore_blinks",
"=",
"False",
")",
":",
"if",
"ignore... | Detect saccades in a stream of gaze location samples.
Coordinates in samplemat are assumed to be in degrees.
Saccades are detect by a velocity/acceleration threshold approach.
A saccade starts when a) the velocity is above threshold, b) the
acceleration is above acc_thresh at least once during the int... | [
"Detect",
"saccades",
"in",
"a",
"stream",
"of",
"gaze",
"location",
"samples",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/samples2fix.py#L33-L98 |
nwilming/ocupy | ocupy/samples2fix.py | fixation_detection | def fixation_detection(samplemat, saccades, Hz=200, samples2fix=None,
respect_trial_borders=False, sample_times=None):
'''
Detect Fixation from saccades.
Fixations are defined as intervals between saccades. This function
also calcuates start and end times (in ms) for each fixatio... | python | def fixation_detection(samplemat, saccades, Hz=200, samples2fix=None,
respect_trial_borders=False, sample_times=None):
'''
Detect Fixation from saccades.
Fixations are defined as intervals between saccades. This function
also calcuates start and end times (in ms) for each fixatio... | [
"def",
"fixation_detection",
"(",
"samplemat",
",",
"saccades",
",",
"Hz",
"=",
"200",
",",
"samples2fix",
"=",
"None",
",",
"respect_trial_borders",
"=",
"False",
",",
"sample_times",
"=",
"None",
")",
":",
"if",
"samples2fix",
"is",
"None",
":",
"samples2f... | Detect Fixation from saccades.
Fixations are defined as intervals between saccades. This function
also calcuates start and end times (in ms) for each fixation.
Input:
samplemat: datamat
Contains the recorded samples and associated metadata.
saccades: ndarray
Logical ... | [
"Detect",
"Fixation",
"from",
"saccades",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/samples2fix.py#L101-L161 |
kurtmckee/listparser | listparser/__init__.py | parse | def parse(parse_obj, agent=None, etag=None, modified=None, inject=False):
"""Parse a subscription list and return a dict containing the results.
:param parse_obj: A file-like object or a string containing a URL, an
absolute or relative filename, or an XML document.
:type parse_obj: str or file
... | python | def parse(parse_obj, agent=None, etag=None, modified=None, inject=False):
"""Parse a subscription list and return a dict containing the results.
:param parse_obj: A file-like object or a string containing a URL, an
absolute or relative filename, or an XML document.
:type parse_obj: str or file
... | [
"def",
"parse",
"(",
"parse_obj",
",",
"agent",
"=",
"None",
",",
"etag",
"=",
"None",
",",
"modified",
"=",
"None",
",",
"inject",
"=",
"False",
")",
":",
"guarantees",
"=",
"common",
".",
"SuperDict",
"(",
"{",
"'bozo'",
":",
"0",
",",
"'feeds'",
... | Parse a subscription list and return a dict containing the results.
:param parse_obj: A file-like object or a string containing a URL, an
absolute or relative filename, or an XML document.
:type parse_obj: str or file
:param agent: User-Agent header to be sent when requesting a URL
:type agent:... | [
"Parse",
"a",
"subscription",
"list",
"and",
"return",
"a",
"dict",
"containing",
"the",
"results",
"."
] | train | https://github.com/kurtmckee/listparser/blob/f9bc310a0ce567cd0611fea68be99974021f53c7/listparser/__init__.py#L71-L144 |
nwilming/ocupy | ocupy/stimuli.py | FixmatStimuliFactory | def FixmatStimuliFactory(fm, loader):
"""
Constructs an categories object for all image / category
combinations in the fixmat.
Parameters:
fm: FixMat
Used for extracting valid category/image combination.
loader: loader
Loader that accesses the stimuli for th... | python | def FixmatStimuliFactory(fm, loader):
"""
Constructs an categories object for all image / category
combinations in the fixmat.
Parameters:
fm: FixMat
Used for extracting valid category/image combination.
loader: loader
Loader that accesses the stimuli for th... | [
"def",
"FixmatStimuliFactory",
"(",
"fm",
",",
"loader",
")",
":",
"# Find all feature names",
"features",
"=",
"[",
"]",
"if",
"loader",
".",
"ftrpath",
":",
"assert",
"os",
".",
"access",
"(",
"loader",
".",
"ftrpath",
",",
"os",
".",
"R_OK",
")",
"fea... | Constructs an categories object for all image / category
combinations in the fixmat.
Parameters:
fm: FixMat
Used for extracting valid category/image combination.
loader: loader
Loader that accesses the stimuli for this fixmat
Returns:
Categories object | [
"Constructs",
"an",
"categories",
"object",
"for",
"all",
"image",
"/",
"category",
"combinations",
"in",
"the",
"fixmat",
".",
"Parameters",
":",
"fm",
":",
"FixMat",
"Used",
"for",
"extracting",
"valid",
"category",
"/",
"image",
"combination",
".",
"loader"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/stimuli.py#L177-L217 |
nwilming/ocupy | ocupy/stimuli.py | DirectoryStimuliFactory | def DirectoryStimuliFactory(loader):
"""
Takes an input path to the images folder of an experiment and generates
automatically the category - filenumber list needed to construct an
appropriate _categories object.
Parameters :
loader : Loader object which contains
impath : s... | python | def DirectoryStimuliFactory(loader):
"""
Takes an input path to the images folder of an experiment and generates
automatically the category - filenumber list needed to construct an
appropriate _categories object.
Parameters :
loader : Loader object which contains
impath : s... | [
"def",
"DirectoryStimuliFactory",
"(",
"loader",
")",
":",
"impath",
"=",
"loader",
".",
"impath",
"ftrpath",
"=",
"loader",
".",
"ftrpath",
"# checks whether user has reading permission for the path",
"assert",
"os",
".",
"access",
"(",
"impath",
",",
"os",
".",
... | Takes an input path to the images folder of an experiment and generates
automatically the category - filenumber list needed to construct an
appropriate _categories object.
Parameters :
loader : Loader object which contains
impath : string
path to the input, i.e. ima... | [
"Takes",
"an",
"input",
"path",
"to",
"the",
"images",
"folder",
"of",
"an",
"experiment",
"and",
"generates",
"automatically",
"the",
"category",
"-",
"filenumber",
"list",
"needed",
"to",
"construct",
"an",
"appropriate",
"_categories",
"object",
".",
"Paramet... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/stimuli.py#L219-L278 |
nwilming/ocupy | ocupy/stimuli.py | Categories.fixations | def fixations(self):
''' Filter the fixmat such that it only contains fixations on images
in categories that are also in the categories object'''
if not self._fixations:
raise RuntimeError('This Images object does not have'
+' an associated fixmat')
if len(lis... | python | def fixations(self):
''' Filter the fixmat such that it only contains fixations on images
in categories that are also in the categories object'''
if not self._fixations:
raise RuntimeError('This Images object does not have'
+' an associated fixmat')
if len(lis... | [
"def",
"fixations",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_fixations",
":",
"raise",
"RuntimeError",
"(",
"'This Images object does not have'",
"+",
"' an associated fixmat'",
")",
"if",
"len",
"(",
"list",
"(",
"self",
".",
"_categories",
".",
"ke... | Filter the fixmat such that it only contains fixations on images
in categories that are also in the categories object | [
"Filter",
"the",
"fixmat",
"such",
"that",
"it",
"only",
"contains",
"fixations",
"on",
"images",
"in",
"categories",
"that",
"are",
"also",
"in",
"the",
"categories",
"object"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/stimuli.py#L49-L61 |
nwilming/ocupy | ocupy/stimuli.py | Image.data | def data(self, value):
"""
Saves a new image to disk
"""
self.loader.save_image(self.category, self.image, value) | python | def data(self, value):
"""
Saves a new image to disk
"""
self.loader.save_image(self.category, self.image, value) | [
"def",
"data",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"loader",
".",
"save_image",
"(",
"self",
".",
"category",
",",
"self",
".",
"image",
",",
"value",
")"
] | Saves a new image to disk | [
"Saves",
"a",
"new",
"image",
"to",
"disk"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/stimuli.py#L140-L144 |
nwilming/ocupy | ocupy/stimuli.py | Image.fixations | def fixations(self):
"""
Returns all fixations that are on this image.
A precondition for this to work is that a fixmat
is associated with this Image object.
"""
if not self._fixations:
raise RuntimeError('This Images object does not have'
+' ... | python | def fixations(self):
"""
Returns all fixations that are on this image.
A precondition for this to work is that a fixmat
is associated with this Image object.
"""
if not self._fixations:
raise RuntimeError('This Images object does not have'
+' ... | [
"def",
"fixations",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_fixations",
":",
"raise",
"RuntimeError",
"(",
"'This Images object does not have'",
"+",
"' an associated fixmat'",
")",
"return",
"self",
".",
"_fixations",
"[",
"(",
"self",
".",
"_fixatio... | Returns all fixations that are on this image.
A precondition for this to work is that a fixmat
is associated with this Image object. | [
"Returns",
"all",
"fixations",
"that",
"are",
"on",
"this",
"image",
".",
"A",
"precondition",
"for",
"this",
"to",
"work",
"is",
"that",
"a",
"fixmat",
"is",
"associated",
"with",
"this",
"Image",
"object",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/stimuli.py#L164-L174 |
nwilming/ocupy | ocupy/xvalidation.py | SimpleXValidation.generate | def generate(self):
"""
Generator for creating the cross-validation slices.
Returns
A tuple of that contains two fixmats (training and test)
and two Category objects (test and train).
"""
for _ in range(0, self.num_slices):
#1. separate fixm... | python | def generate(self):
"""
Generator for creating the cross-validation slices.
Returns
A tuple of that contains two fixmats (training and test)
and two Category objects (test and train).
"""
for _ in range(0, self.num_slices):
#1. separate fixm... | [
"def",
"generate",
"(",
"self",
")",
":",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"self",
".",
"num_slices",
")",
":",
"#1. separate fixmat into test and training fixmat",
"subjects",
"=",
"np",
".",
"unique",
"(",
"self",
".",
"fm",
".",
"SUBJECTINDEX",
... | Generator for creating the cross-validation slices.
Returns
A tuple of that contains two fixmats (training and test)
and two Category objects (test and train). | [
"Generator",
"for",
"creating",
"the",
"cross",
"-",
"validation",
"slices",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/xvalidation.py#L42-L88 |
nwilming/ocupy | ocupy/saccade_geometry.py | prepare_data | def prepare_data(fm, max_back, dur_cap=700):
'''
Computes angle and length differences up to given order and deletes
suspiciously long fixations.
Input
fm: Fixmat
Fixmat for which to comput angle and length differences
max_back: Int
Computes delta angle and ampli... | python | def prepare_data(fm, max_back, dur_cap=700):
'''
Computes angle and length differences up to given order and deletes
suspiciously long fixations.
Input
fm: Fixmat
Fixmat for which to comput angle and length differences
max_back: Int
Computes delta angle and ampli... | [
"def",
"prepare_data",
"(",
"fm",
",",
"max_back",
",",
"dur_cap",
"=",
"700",
")",
":",
"durations",
"=",
"np",
".",
"roll",
"(",
"fm",
".",
"end",
"-",
"fm",
".",
"start",
",",
"1",
")",
".",
"astype",
"(",
"float",
")",
"angles",
",",
"lengths... | Computes angle and length differences up to given order and deletes
suspiciously long fixations.
Input
fm: Fixmat
Fixmat for which to comput angle and length differences
max_back: Int
Computes delta angle and amplitude up to order max_back.
dur_cap: Int
... | [
"Computes",
"angle",
"and",
"length",
"differences",
"up",
"to",
"given",
"order",
"and",
"deletes",
"suspiciously",
"long",
"fixations",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/saccade_geometry.py#L15-L48 |
nwilming/ocupy | ocupy/saccade_geometry.py | saccadic_momentum_effect | def saccadic_momentum_effect(durations, forward_angle,
summary_stat=nanmean):
"""
Computes the mean fixation duration at forward angles.
"""
durations_per_da = np.nan * np.ones((len(e_angle) - 1,))
for i, (bo, b1) in enumerate(zip(e_angle[:-1], e_angle[1:])):
idx... | python | def saccadic_momentum_effect(durations, forward_angle,
summary_stat=nanmean):
"""
Computes the mean fixation duration at forward angles.
"""
durations_per_da = np.nan * np.ones((len(e_angle) - 1,))
for i, (bo, b1) in enumerate(zip(e_angle[:-1], e_angle[1:])):
idx... | [
"def",
"saccadic_momentum_effect",
"(",
"durations",
",",
"forward_angle",
",",
"summary_stat",
"=",
"nanmean",
")",
":",
"durations_per_da",
"=",
"np",
".",
"nan",
"*",
"np",
".",
"ones",
"(",
"(",
"len",
"(",
"e_angle",
")",
"-",
"1",
",",
")",
")",
... | Computes the mean fixation duration at forward angles. | [
"Computes",
"the",
"mean",
"fixation",
"duration",
"at",
"forward",
"angles",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/saccade_geometry.py#L51-L63 |
nwilming/ocupy | ocupy/saccade_geometry.py | ior_effect | def ior_effect(durations, angle_diffs, length_diffs,
summary_stat=np.mean, parallel=True, min_samples=20):
"""
Computes a measure of fixation durations at delta angle and delta
length combinations.
"""
raster = np.empty((len(e_dist) - 1, len(e_angle) - 1), dtype=object)
for a, (a_... | python | def ior_effect(durations, angle_diffs, length_diffs,
summary_stat=np.mean, parallel=True, min_samples=20):
"""
Computes a measure of fixation durations at delta angle and delta
length combinations.
"""
raster = np.empty((len(e_dist) - 1, len(e_angle) - 1), dtype=object)
for a, (a_... | [
"def",
"ior_effect",
"(",
"durations",
",",
"angle_diffs",
",",
"length_diffs",
",",
"summary_stat",
"=",
"np",
".",
"mean",
",",
"parallel",
"=",
"True",
",",
"min_samples",
"=",
"20",
")",
":",
"raster",
"=",
"np",
".",
"empty",
"(",
"(",
"len",
"(",... | Computes a measure of fixation durations at delta angle and delta
length combinations. | [
"Computes",
"a",
"measure",
"of",
"fixation",
"durations",
"at",
"delta",
"angle",
"and",
"delta",
"length",
"combinations",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/saccade_geometry.py#L66-L90 |
nwilming/ocupy | ocupy/saccade_geometry.py | predict_fixation_duration | def predict_fixation_duration(
durations, angles, length_diffs, dataset=None, params=None):
"""
Fits a non-linear piecewise regression to fixtaion durations for a fixmat.
Returns corrected fixation durations.
"""
if dataset is None:
dataset = np.ones(durations.shape)
corrected_d... | python | def predict_fixation_duration(
durations, angles, length_diffs, dataset=None, params=None):
"""
Fits a non-linear piecewise regression to fixtaion durations for a fixmat.
Returns corrected fixation durations.
"""
if dataset is None:
dataset = np.ones(durations.shape)
corrected_d... | [
"def",
"predict_fixation_duration",
"(",
"durations",
",",
"angles",
",",
"length_diffs",
",",
"dataset",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"dataset",
"is",
"None",
":",
"dataset",
"=",
"np",
".",
"ones",
"(",
"durations",
".",
"sh... | Fits a non-linear piecewise regression to fixtaion durations for a fixmat.
Returns corrected fixation durations. | [
"Fits",
"a",
"non",
"-",
"linear",
"piecewise",
"regression",
"to",
"fixtaion",
"durations",
"for",
"a",
"fixmat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/saccade_geometry.py#L93-L122 |
nwilming/ocupy | ocupy/saccade_geometry.py | subject_predictions | def subject_predictions(fm, field='SUBJECTINDEX',
method=predict_fixation_duration, data=None):
'''
Calculates the saccadic momentum effect for individual subjects.
Removes any effect of amplitude differences.
The parameters are fitted on unbinned data. The effects are
comp... | python | def subject_predictions(fm, field='SUBJECTINDEX',
method=predict_fixation_duration, data=None):
'''
Calculates the saccadic momentum effect for individual subjects.
Removes any effect of amplitude differences.
The parameters are fitted on unbinned data. The effects are
comp... | [
"def",
"subject_predictions",
"(",
"fm",
",",
"field",
"=",
"'SUBJECTINDEX'",
",",
"method",
"=",
"predict_fixation_duration",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"fma",
",",
"dura",
",",
"faa",
",",
"adsa",
",",
"ldsa",
... | Calculates the saccadic momentum effect for individual subjects.
Removes any effect of amplitude differences.
The parameters are fitted on unbinned data. The effects are
computed on binned data. See e_dist and e_angle for the binning
parameter. | [
"Calculates",
"the",
"saccadic",
"momentum",
"effect",
"for",
"individual",
"subjects",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/saccade_geometry.py#L125-L158 |
nwilming/ocupy | ocupy/bounds.py | intersubject_scores | def intersubject_scores(fm, category, predicting_filenumbers,
predicting_subjects, predicted_filenumbers,
predicted_subjects, controls = True, scale_factor = 1):
"""
Calculates how well the fixations from a set of subjects on a set of
images can be predicted w... | python | def intersubject_scores(fm, category, predicting_filenumbers,
predicting_subjects, predicted_filenumbers,
predicted_subjects, controls = True, scale_factor = 1):
"""
Calculates how well the fixations from a set of subjects on a set of
images can be predicted w... | [
"def",
"intersubject_scores",
"(",
"fm",
",",
"category",
",",
"predicting_filenumbers",
",",
"predicting_subjects",
",",
"predicted_filenumbers",
",",
"predicted_subjects",
",",
"controls",
"=",
"True",
",",
"scale_factor",
"=",
"1",
")",
":",
"predicting_fm",
"=",... | Calculates how well the fixations from a set of subjects on a set of
images can be predicted with the fixations from another set of subjects
on another set of images.
The prediction is carried out by computing a fixation density map from
fixations of predicting_subjects subjects on predicting_images im... | [
"Calculates",
"how",
"well",
"the",
"fixations",
"from",
"a",
"set",
"of",
"subjects",
"on",
"a",
"set",
"of",
"images",
"can",
"be",
"predicted",
"with",
"the",
"fixations",
"from",
"another",
"set",
"of",
"subjects",
"on",
"another",
"set",
"of",
"images... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/bounds.py#L12-L76 |
nwilming/ocupy | ocupy/bounds.py | intersubject_scores_random_subjects | def intersubject_scores_random_subjects(fm, category, filenumber, n_train,
n_predict, controls=True,
scale_factor = 1):
"""
Calculates how well the fixations of n random subjects on one image can
be predicted with the fixations ... | python | def intersubject_scores_random_subjects(fm, category, filenumber, n_train,
n_predict, controls=True,
scale_factor = 1):
"""
Calculates how well the fixations of n random subjects on one image can
be predicted with the fixations ... | [
"def",
"intersubject_scores_random_subjects",
"(",
"fm",
",",
"category",
",",
"filenumber",
",",
"n_train",
",",
"n_predict",
",",
"controls",
"=",
"True",
",",
"scale_factor",
"=",
"1",
")",
":",
"subjects",
"=",
"np",
".",
"unique",
"(",
"fm",
".",
"SUB... | Calculates how well the fixations of n random subjects on one image can
be predicted with the fixations of m other random subjects.
Notes
Function that uses intersubject_auc for computing auc.
Parameters
fm : fixmat instance
category : int
Category from which the fixati... | [
"Calculates",
"how",
"well",
"the",
"fixations",
"of",
"n",
"random",
"subjects",
"on",
"one",
"image",
"can",
"be",
"predicted",
"with",
"the",
"fixations",
"of",
"m",
"other",
"random",
"subjects",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/bounds.py#L78-L121 |
nwilming/ocupy | ocupy/bounds.py | upper_bound | def upper_bound(fm, nr_subs = None, scale_factor = 1):
"""
compute the inter-subject consistency upper bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minus 1... | python | def upper_bound(fm, nr_subs = None, scale_factor = 1):
"""
compute the inter-subject consistency upper bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minus 1... | [
"def",
"upper_bound",
"(",
"fm",
",",
"nr_subs",
"=",
"None",
",",
"scale_factor",
"=",
"1",
")",
":",
"nr_subs_total",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"fm",
".",
"SUBJECTINDEX",
")",
")",
"if",
"not",
"nr_subs",
":",
"nr_subs",
"=",
"nr_s... | compute the inter-subject consistency upper bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minus 1
scale_factor : the scale factor of the FDMs. Default is 1.... | [
"compute",
"the",
"inter",
"-",
"subject",
"consistency",
"upper",
"bound",
"for",
"a",
"fixmat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/bounds.py#L123-L173 |
nwilming/ocupy | ocupy/bounds.py | lower_bound | def lower_bound(fm, nr_subs = None, nr_imgs = None, scale_factor = 1):
"""
Compute the spatial bias lower bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minu... | python | def lower_bound(fm, nr_subs = None, nr_imgs = None, scale_factor = 1):
"""
Compute the spatial bias lower bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minu... | [
"def",
"lower_bound",
"(",
"fm",
",",
"nr_subs",
"=",
"None",
",",
"nr_imgs",
"=",
"None",
",",
"scale_factor",
"=",
"1",
")",
":",
"nr_subs_total",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"fm",
".",
"SUBJECTINDEX",
")",
")",
"if",
"nr_subs",
"is"... | Compute the spatial bias lower bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minus 1
nr_imgs : the number of images used for prediction. If given, the
... | [
"Compute",
"the",
"spatial",
"bias",
"lower",
"bound",
"for",
"a",
"fixmat",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/bounds.py#L175-L243 |
nwilming/ocupy | ocupy/parallel.py | ind2sub | def ind2sub(ind, dimensions):
"""
Calculates subscripts for indices into regularly spaced matrixes.
"""
# check that the index is within range
if ind >= np.prod(dimensions):
raise RuntimeError("ind2sub: index exceeds array size")
cum_dims = list(dimensions)
cum_dims.reverse()
m =... | python | def ind2sub(ind, dimensions):
"""
Calculates subscripts for indices into regularly spaced matrixes.
"""
# check that the index is within range
if ind >= np.prod(dimensions):
raise RuntimeError("ind2sub: index exceeds array size")
cum_dims = list(dimensions)
cum_dims.reverse()
m =... | [
"def",
"ind2sub",
"(",
"ind",
",",
"dimensions",
")",
":",
"# check that the index is within range",
"if",
"ind",
">=",
"np",
".",
"prod",
"(",
"dimensions",
")",
":",
"raise",
"RuntimeError",
"(",
"\"ind2sub: index exceeds array size\"",
")",
"cum_dims",
"=",
"li... | Calculates subscripts for indices into regularly spaced matrixes. | [
"Calculates",
"subscripts",
"for",
"indices",
"into",
"regularly",
"spaced",
"matrixes",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L268-L289 |
nwilming/ocupy | ocupy/parallel.py | sub2ind | def sub2ind(indices, dimensions):
"""
An exemplary sub2ind implementation to create randomization
scripts.
This function calculates indices from subscripts into regularly spaced
matrixes.
"""
# check that none of the indices exceeds the size of the array
if any([i > j for i, j in zip(... | python | def sub2ind(indices, dimensions):
"""
An exemplary sub2ind implementation to create randomization
scripts.
This function calculates indices from subscripts into regularly spaced
matrixes.
"""
# check that none of the indices exceeds the size of the array
if any([i > j for i, j in zip(... | [
"def",
"sub2ind",
"(",
"indices",
",",
"dimensions",
")",
":",
"# check that none of the indices exceeds the size of the array",
"if",
"any",
"(",
"[",
"i",
">",
"j",
"for",
"i",
",",
"j",
"in",
"zip",
"(",
"indices",
",",
"dimensions",
")",
"]",
")",
":",
... | An exemplary sub2ind implementation to create randomization
scripts.
This function calculates indices from subscripts into regularly spaced
matrixes. | [
"An",
"exemplary",
"sub2ind",
"implementation",
"to",
"create",
"randomization",
"scripts",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L292-L314 |
nwilming/ocupy | ocupy/parallel.py | RestoreTaskStoreFactory | def RestoreTaskStoreFactory(store_class, chunk_size, restore_file, save_file):
"""
Restores a task store from file.
"""
intm_results = np.load(restore_file)
intm = intm_results[intm_results.files[0]]
idx = np.isnan(intm).flatten().nonzero()[0]
partitions = math.ceil(len(idx) / float(chunk_si... | python | def RestoreTaskStoreFactory(store_class, chunk_size, restore_file, save_file):
"""
Restores a task store from file.
"""
intm_results = np.load(restore_file)
intm = intm_results[intm_results.files[0]]
idx = np.isnan(intm).flatten().nonzero()[0]
partitions = math.ceil(len(idx) / float(chunk_si... | [
"def",
"RestoreTaskStoreFactory",
"(",
"store_class",
",",
"chunk_size",
",",
"restore_file",
",",
"save_file",
")",
":",
"intm_results",
"=",
"np",
".",
"load",
"(",
"restore_file",
")",
"intm",
"=",
"intm_results",
"[",
"intm_results",
".",
"files",
"[",
"0"... | Restores a task store from file. | [
"Restores",
"a",
"task",
"store",
"from",
"file",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L316-L329 |
nwilming/ocupy | ocupy/parallel.py | TaskManager.xmlrpc_reschedule | def xmlrpc_reschedule(self):
"""
Reschedule all running tasks.
"""
if not len(self.scheduled_tasks) == 0:
self.reschedule = list(self.scheduled_tasks.items())
self.scheduled_tasks = {}
return True | python | def xmlrpc_reschedule(self):
"""
Reschedule all running tasks.
"""
if not len(self.scheduled_tasks) == 0:
self.reschedule = list(self.scheduled_tasks.items())
self.scheduled_tasks = {}
return True | [
"def",
"xmlrpc_reschedule",
"(",
"self",
")",
":",
"if",
"not",
"len",
"(",
"self",
".",
"scheduled_tasks",
")",
"==",
"0",
":",
"self",
".",
"reschedule",
"=",
"list",
"(",
"self",
".",
"scheduled_tasks",
".",
"items",
"(",
")",
")",
"self",
".",
"s... | Reschedule all running tasks. | [
"Reschedule",
"all",
"running",
"tasks",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L61-L68 |
nwilming/ocupy | ocupy/parallel.py | TaskManager.xmlrpc_get_task | def xmlrpc_get_task(self):
"""
Return a new task description: ID and necessary parameters,
all are given in a dictionary
"""
try:
if len(self.reschedule) == 0:
(task_id, cur_task) = next(self.task_iterator)
else:
(task_id, ... | python | def xmlrpc_get_task(self):
"""
Return a new task description: ID and necessary parameters,
all are given in a dictionary
"""
try:
if len(self.reschedule) == 0:
(task_id, cur_task) = next(self.task_iterator)
else:
(task_id, ... | [
"def",
"xmlrpc_get_task",
"(",
"self",
")",
":",
"try",
":",
"if",
"len",
"(",
"self",
".",
"reschedule",
")",
"==",
"0",
":",
"(",
"task_id",
",",
"cur_task",
")",
"=",
"next",
"(",
"self",
".",
"task_iterator",
")",
"else",
":",
"(",
"task_id",
"... | Return a new task description: ID and necessary parameters,
all are given in a dictionary | [
"Return",
"a",
"new",
"task",
"description",
":",
"ID",
"and",
"necessary",
"parameters",
"all",
"are",
"given",
"in",
"a",
"dictionary"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L70-L88 |
nwilming/ocupy | ocupy/parallel.py | TaskManager.xmlrpc_task_done | def xmlrpc_task_done(self, result):
"""
Take the results of a computation and put it into the results list.
"""
(task_id, task_results) = result
del self.scheduled_tasks[task_id]
self.task_store.update_results(task_id, task_results)
self.results += 1
retur... | python | def xmlrpc_task_done(self, result):
"""
Take the results of a computation and put it into the results list.
"""
(task_id, task_results) = result
del self.scheduled_tasks[task_id]
self.task_store.update_results(task_id, task_results)
self.results += 1
retur... | [
"def",
"xmlrpc_task_done",
"(",
"self",
",",
"result",
")",
":",
"(",
"task_id",
",",
"task_results",
")",
"=",
"result",
"del",
"self",
".",
"scheduled_tasks",
"[",
"task_id",
"]",
"self",
".",
"task_store",
".",
"update_results",
"(",
"task_id",
",",
"ta... | Take the results of a computation and put it into the results list. | [
"Take",
"the",
"results",
"of",
"a",
"computation",
"and",
"put",
"it",
"into",
"the",
"results",
"list",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L90-L98 |
nwilming/ocupy | ocupy/parallel.py | TaskManager.xmlrpc_status | def xmlrpc_status(self):
"""
Return a status message
"""
return ("""
%i Jobs are still wating for execution
%i Jobs are being processed
%i Jobs are done
""" %(self.task_store.partitions -
self.results -
len(self.scheduled_... | python | def xmlrpc_status(self):
"""
Return a status message
"""
return ("""
%i Jobs are still wating for execution
%i Jobs are being processed
%i Jobs are done
""" %(self.task_store.partitions -
self.results -
len(self.scheduled_... | [
"def",
"xmlrpc_status",
"(",
"self",
")",
":",
"return",
"(",
"\"\"\"\n %i Jobs are still wating for execution\n %i Jobs are being processed\n %i Jobs are done\n \"\"\"",
"%",
"(",
"self",
".",
"task_store",
".",
"partitions",
"-",
"self",
".",
"resu... | Return a status message | [
"Return",
"a",
"status",
"message"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L100-L112 |
nwilming/ocupy | ocupy/parallel.py | TaskManager.xmlrpc_save2file | def xmlrpc_save2file(self, filename):
"""
Save results and own state into file.
"""
savefile = open(filename,'wb')
try:
pickle.dump({'scheduled':self.scheduled_tasks,
'reschedule':self.reschedule},savefile)
except pickle.PicklingError... | python | def xmlrpc_save2file(self, filename):
"""
Save results and own state into file.
"""
savefile = open(filename,'wb')
try:
pickle.dump({'scheduled':self.scheduled_tasks,
'reschedule':self.reschedule},savefile)
except pickle.PicklingError... | [
"def",
"xmlrpc_save2file",
"(",
"self",
",",
"filename",
")",
":",
"savefile",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"try",
":",
"pickle",
".",
"dump",
"(",
"{",
"'scheduled'",
":",
"self",
".",
"scheduled_tasks",
",",
"'reschedule'",
":",
"sel... | Save results and own state into file. | [
"Save",
"results",
"and",
"own",
"state",
"into",
"file",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L114-L125 |
nwilming/ocupy | ocupy/parallel.py | Worker.run | def run(self):
"""This function needs to be called to start the computation."""
(task_id, tasks) = self.server.get_task()
self.task_store.from_dict(tasks)
for (index, task) in self.task_store:
result = self.compute(index, task)
self.results.append(result)
... | python | def run(self):
"""This function needs to be called to start the computation."""
(task_id, tasks) = self.server.get_task()
self.task_store.from_dict(tasks)
for (index, task) in self.task_store:
result = self.compute(index, task)
self.results.append(result)
... | [
"def",
"run",
"(",
"self",
")",
":",
"(",
"task_id",
",",
"tasks",
")",
"=",
"self",
".",
"server",
".",
"get_task",
"(",
")",
"self",
".",
"task_store",
".",
"from_dict",
"(",
"tasks",
")",
"for",
"(",
"index",
",",
"task",
")",
"in",
"self",
".... | This function needs to be called to start the computation. | [
"This",
"function",
"needs",
"to",
"be",
"called",
"to",
"start",
"the",
"computation",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L158-L165 |
nwilming/ocupy | ocupy/parallel.py | TaskStore.from_dict | def from_dict(self, description):
"""Configures the task store to be the task_store described
in description"""
assert(self.ident == description['ident'])
self.partitions = description['partitions']
self.indices = description['indices'] | python | def from_dict(self, description):
"""Configures the task store to be the task_store described
in description"""
assert(self.ident == description['ident'])
self.partitions = description['partitions']
self.indices = description['indices'] | [
"def",
"from_dict",
"(",
"self",
",",
"description",
")",
":",
"assert",
"(",
"self",
".",
"ident",
"==",
"description",
"[",
"'ident'",
"]",
")",
"self",
".",
"partitions",
"=",
"description",
"[",
"'partitions'",
"]",
"self",
".",
"indices",
"=",
"desc... | Configures the task store to be the task_store described
in description | [
"Configures",
"the",
"task",
"store",
"to",
"be",
"the",
"task_store",
"described",
"in",
"description"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L216-L221 |
nwilming/ocupy | ocupy/parallel.py | TaskStore.partition | def partition(self):
"""Partitions all tasks into groups of tasks. A group is
represented by a task_store object that indexes a sub-
set of tasks."""
step = int(math.ceil(self.num_tasks / float(self.partitions)))
if self.indices == None:
slice_ind = list(range(0... | python | def partition(self):
"""Partitions all tasks into groups of tasks. A group is
represented by a task_store object that indexes a sub-
set of tasks."""
step = int(math.ceil(self.num_tasks / float(self.partitions)))
if self.indices == None:
slice_ind = list(range(0... | [
"def",
"partition",
"(",
"self",
")",
":",
"step",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"self",
".",
"num_tasks",
"/",
"float",
"(",
"self",
".",
"partitions",
")",
")",
")",
"if",
"self",
".",
"indices",
"==",
"None",
":",
"slice_ind",
"=",
... | Partitions all tasks into groups of tasks. A group is
represented by a task_store object that indexes a sub-
set of tasks. | [
"Partitions",
"all",
"tasks",
"into",
"groups",
"of",
"tasks",
".",
"A",
"group",
"is",
"represented",
"by",
"a",
"task_store",
"object",
"that",
"indexes",
"a",
"sub",
"-",
"set",
"of",
"tasks",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L228-L245 |
nwilming/ocupy | ocupy/spline_base.py | fit3d | def fit3d(samples, e_x, e_y, e_z, remove_zeros = False, **kw):
"""Fits a 3D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e_x: Array
Edges that define the events in the probability
distribution along the x ... | python | def fit3d(samples, e_x, e_y, e_z, remove_zeros = False, **kw):
"""Fits a 3D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e_x: Array
Edges that define the events in the probability
distribution along the x ... | [
"def",
"fit3d",
"(",
"samples",
",",
"e_x",
",",
"e_y",
",",
"e_z",
",",
"remove_zeros",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"height",
",",
"width",
",",
"depth",
"=",
"len",
"(",
"e_y",
")",
"-",
"1",
",",
"len",
"(",
"e_x",
")",
"-... | Fits a 3D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e_x: Array
Edges that define the events in the probability
distribution along the x direction. For example,
e_x[0] < samples[0] <= e_x[1] pic... | [
"Fits",
"a",
"3D",
"distribution",
"with",
"splines",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L9-L48 |
nwilming/ocupy | ocupy/spline_base.py | fit2d | def fit2d(samples,e_x, e_y, remove_zeros = False, p_est = None, **kw):
"""Fits a 2D distribution with splines.
Input:
samples: Matrix or list of arrays
If matrix, it must be of size Nx2, where N is the number of
observations. If list, it must contain two arrays of length
... | python | def fit2d(samples,e_x, e_y, remove_zeros = False, p_est = None, **kw):
"""Fits a 2D distribution with splines.
Input:
samples: Matrix or list of arrays
If matrix, it must be of size Nx2, where N is the number of
observations. If list, it must contain two arrays of length
... | [
"def",
"fit2d",
"(",
"samples",
",",
"e_x",
",",
"e_y",
",",
"remove_zeros",
"=",
"False",
",",
"p_est",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"p_est",
"is",
"None",
":",
"height",
"=",
"len",
"(",
"e_y",
")",
"-",
"1",
"width",
"="... | Fits a 2D distribution with splines.
Input:
samples: Matrix or list of arrays
If matrix, it must be of size Nx2, where N is the number of
observations. If list, it must contain two arrays of length
N.
e_x: Array
Edges that define the events in the pr... | [
"Fits",
"a",
"2D",
"distribution",
"with",
"splines",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L51-L103 |
nwilming/ocupy | ocupy/spline_base.py | fit1d | def fit1d(samples, e, remove_zeros = False, **kw):
"""Fits a 1D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e: Array
Edges that define the events in the probability
distribution. For example, e[0] < x <= ... | python | def fit1d(samples, e, remove_zeros = False, **kw):
"""Fits a 1D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e: Array
Edges that define the events in the probability
distribution. For example, e[0] < x <= ... | [
"def",
"fit1d",
"(",
"samples",
",",
"e",
",",
"remove_zeros",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"samples",
"=",
"samples",
"[",
"~",
"np",
".",
"isnan",
"(",
"samples",
")",
"]",
"length",
"=",
"len",
"(",
"e",
")",
"-",
"1",
"hist"... | Fits a 1D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e: Array
Edges that define the events in the probability
distribution. For example, e[0] < x <= e[1] is
the range of values that are associate... | [
"Fits",
"a",
"1D",
"distribution",
"with",
"splines",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L105-L137 |
nwilming/ocupy | ocupy/spline_base.py | knots_from_marginal | def knots_from_marginal(marginal, nr_knots, spline_order):
"""
Determines knot placement based on a marginal distribution.
It places knots such that each knot covers the same amount
of probability mass. Two of the knots are reserved for the
borders which are treated seperatly. For example, a uni... | python | def knots_from_marginal(marginal, nr_knots, spline_order):
"""
Determines knot placement based on a marginal distribution.
It places knots such that each knot covers the same amount
of probability mass. Two of the knots are reserved for the
borders which are treated seperatly. For example, a uni... | [
"def",
"knots_from_marginal",
"(",
"marginal",
",",
"nr_knots",
",",
"spline_order",
")",
":",
"cumsum",
"=",
"np",
".",
"cumsum",
"(",
"marginal",
")",
"cumsum",
"=",
"cumsum",
"/",
"cumsum",
".",
"max",
"(",
")",
"borders",
"=",
"np",
".",
"linspace",
... | Determines knot placement based on a marginal distribution.
It places knots such that each knot covers the same amount
of probability mass. Two of the knots are reserved for the
borders which are treated seperatly. For example, a uniform
distribution with 5 knots will cause the knots to be equally
... | [
"Determines",
"knot",
"placement",
"based",
"on",
"a",
"marginal",
"distribution",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L139-L168 |
nwilming/ocupy | ocupy/spline_base.py | spline_base1d | def spline_base1d(length, nr_knots = 20, spline_order = 5, marginal = None):
"""Computes a 1D spline basis
Input:
length: int
length of each basis
nr_knots: int
Number of knots, i.e. number of basis functions.
spline_order: int
Order of the splin... | python | def spline_base1d(length, nr_knots = 20, spline_order = 5, marginal = None):
"""Computes a 1D spline basis
Input:
length: int
length of each basis
nr_knots: int
Number of knots, i.e. number of basis functions.
spline_order: int
Order of the splin... | [
"def",
"spline_base1d",
"(",
"length",
",",
"nr_knots",
"=",
"20",
",",
"spline_order",
"=",
"5",
",",
"marginal",
"=",
"None",
")",
":",
"if",
"marginal",
"is",
"None",
":",
"knots",
"=",
"augknt",
"(",
"np",
".",
"linspace",
"(",
"0",
",",
"length"... | Computes a 1D spline basis
Input:
length: int
length of each basis
nr_knots: int
Number of knots, i.e. number of basis functions.
spline_order: int
Order of the splines.
marginal: array, optional
Estimate of the marginal distribut... | [
"Computes",
"a",
"1D",
"spline",
"basis",
"Input",
":",
"length",
":",
"int",
"length",
"of",
"each",
"basis",
"nr_knots",
":",
"int",
"Number",
"of",
"knots",
"i",
".",
"e",
".",
"number",
"of",
"basis",
"functions",
".",
"spline_order",
":",
"int",
"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L171-L194 |
nwilming/ocupy | ocupy/spline_base.py | spline_base2d | def spline_base2d(width, height, nr_knots_x = 20.0, nr_knots_y = 20.0,
spline_order = 5, marginal_x = None, marginal_y = None):
"""Computes a set of 2D spline basis functions.
The basis functions cover the entire space in height*width and can
for example be used to create fixation density ma... | python | def spline_base2d(width, height, nr_knots_x = 20.0, nr_knots_y = 20.0,
spline_order = 5, marginal_x = None, marginal_y = None):
"""Computes a set of 2D spline basis functions.
The basis functions cover the entire space in height*width and can
for example be used to create fixation density ma... | [
"def",
"spline_base2d",
"(",
"width",
",",
"height",
",",
"nr_knots_x",
"=",
"20.0",
",",
"nr_knots_y",
"=",
"20.0",
",",
"spline_order",
"=",
"5",
",",
"marginal_x",
"=",
"None",
",",
"marginal_y",
"=",
"None",
")",
":",
"if",
"not",
"(",
"nr_knots_x",
... | Computes a set of 2D spline basis functions.
The basis functions cover the entire space in height*width and can
for example be used to create fixation density maps.
Input:
width: int
width of each basis
height: int
height of each basis
nr_knots_x: i... | [
"Computes",
"a",
"set",
"of",
"2D",
"spline",
"basis",
"functions",
".",
"The",
"basis",
"functions",
"cover",
"the",
"entire",
"space",
"in",
"height",
"*",
"width",
"and",
"can",
"for",
"example",
"be",
"used",
"to",
"create",
"fixation",
"density",
"map... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L197-L257 |
nwilming/ocupy | ocupy/spline_base.py | spline_base3d | def spline_base3d( width, height, depth, nr_knots_x = 10.0, nr_knots_y = 10.0,
nr_knots_z=10, spline_order = 3, marginal_x = None, marginal_y = None,
marginal_z = None):
"""Computes a set of 3D spline basis functions.
For a description of the parameters see spline_base2d.
"""
if... | python | def spline_base3d( width, height, depth, nr_knots_x = 10.0, nr_knots_y = 10.0,
nr_knots_z=10, spline_order = 3, marginal_x = None, marginal_y = None,
marginal_z = None):
"""Computes a set of 3D spline basis functions.
For a description of the parameters see spline_base2d.
"""
if... | [
"def",
"spline_base3d",
"(",
"width",
",",
"height",
",",
"depth",
",",
"nr_knots_x",
"=",
"10.0",
",",
"nr_knots_y",
"=",
"10.0",
",",
"nr_knots_z",
"=",
"10",
",",
"spline_order",
"=",
"3",
",",
"marginal_x",
"=",
"None",
",",
"marginal_y",
"=",
"None"... | Computes a set of 3D spline basis functions.
For a description of the parameters see spline_base2d. | [
"Computes",
"a",
"set",
"of",
"3D",
"spline",
"basis",
"functions",
".",
"For",
"a",
"description",
"of",
"the",
"parameters",
"see",
"spline_base2d",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L259-L283 |
nwilming/ocupy | ocupy/spline_base.py | spline | def spline(x,knots,p,i=0.0):
"""Evaluates the ith spline basis given by knots on points in x"""
assert(p+1<len(knots))
return np.array([N(float(u),float(i),float(p),knots) for u in x]) | python | def spline(x,knots,p,i=0.0):
"""Evaluates the ith spline basis given by knots on points in x"""
assert(p+1<len(knots))
return np.array([N(float(u),float(i),float(p),knots) for u in x]) | [
"def",
"spline",
"(",
"x",
",",
"knots",
",",
"p",
",",
"i",
"=",
"0.0",
")",
":",
"assert",
"(",
"p",
"+",
"1",
"<",
"len",
"(",
"knots",
")",
")",
"return",
"np",
".",
"array",
"(",
"[",
"N",
"(",
"float",
"(",
"u",
")",
",",
"float",
"... | Evaluates the ith spline basis given by knots on points in x | [
"Evaluates",
"the",
"ith",
"spline",
"basis",
"given",
"by",
"knots",
"on",
"points",
"in",
"x"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L285-L288 |
nwilming/ocupy | ocupy/spline_base.py | spcol | def spcol(x,knots,spline_order):
"""Computes the spline colocation matrix for knots in x.
The spline collocation matrix contains all m-p-1 bases
defined by knots. Specifically it contains the ith basis
in the ith column.
Input:
x: vector to evaluate the bases on
knots: vec... | python | def spcol(x,knots,spline_order):
"""Computes the spline colocation matrix for knots in x.
The spline collocation matrix contains all m-p-1 bases
defined by knots. Specifically it contains the ith basis
in the ith column.
Input:
x: vector to evaluate the bases on
knots: vec... | [
"def",
"spcol",
"(",
"x",
",",
"knots",
",",
"spline_order",
")",
":",
"colmat",
"=",
"np",
".",
"nan",
"*",
"np",
".",
"ones",
"(",
"(",
"len",
"(",
"x",
")",
",",
"len",
"(",
"knots",
")",
"-",
"spline_order",
"-",
"1",
")",
")",
"for",
"i"... | Computes the spline colocation matrix for knots in x.
The spline collocation matrix contains all m-p-1 bases
defined by knots. Specifically it contains the ith basis
in the ith column.
Input:
x: vector to evaluate the bases on
knots: vector of knots
spline_order: orde... | [
"Computes",
"the",
"spline",
"colocation",
"matrix",
"for",
"knots",
"in",
"x",
".",
"The",
"spline",
"collocation",
"matrix",
"contains",
"all",
"m",
"-",
"p",
"-",
"1",
"bases",
"defined",
"by",
"knots",
".",
"Specifically",
"it",
"contains",
"the",
"ith... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L290-L311 |
nwilming/ocupy | ocupy/spline_base.py | augknt | def augknt(knots,order):
"""Augment knot sequence such that some boundary conditions
are met."""
a = []
[a.append(knots[0]) for t in range(0,order)]
[a.append(k) for k in knots]
[a.append(knots[-1]) for t in range(0,order)]
return np.array(a) | python | def augknt(knots,order):
"""Augment knot sequence such that some boundary conditions
are met."""
a = []
[a.append(knots[0]) for t in range(0,order)]
[a.append(k) for k in knots]
[a.append(knots[-1]) for t in range(0,order)]
return np.array(a) | [
"def",
"augknt",
"(",
"knots",
",",
"order",
")",
":",
"a",
"=",
"[",
"]",
"[",
"a",
".",
"append",
"(",
"knots",
"[",
"0",
"]",
")",
"for",
"t",
"in",
"range",
"(",
"0",
",",
"order",
")",
"]",
"[",
"a",
".",
"append",
"(",
"k",
")",
"fo... | Augment knot sequence such that some boundary conditions
are met. | [
"Augment",
"knot",
"sequence",
"such",
"that",
"some",
"boundary",
"conditions",
"are",
"met",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L313-L320 |
nwilming/ocupy | ocupy/spline_base.py | N | def N(u,i,p,knots):
"""Compute Spline Basis
Evaluates the spline basis of order p defined by knots
at knot i and point u.
"""
if p == 0:
if knots[i] < u and u <=knots[i+1]:
return 1.0
else:
return 0.0
else:
try:
k = (( float((u-kn... | python | def N(u,i,p,knots):
"""Compute Spline Basis
Evaluates the spline basis of order p defined by knots
at knot i and point u.
"""
if p == 0:
if knots[i] < u and u <=knots[i+1]:
return 1.0
else:
return 0.0
else:
try:
k = (( float((u-kn... | [
"def",
"N",
"(",
"u",
",",
"i",
",",
"p",
",",
"knots",
")",
":",
"if",
"p",
"==",
"0",
":",
"if",
"knots",
"[",
"i",
"]",
"<",
"u",
"and",
"u",
"<=",
"knots",
"[",
"i",
"+",
"1",
"]",
":",
"return",
"1.0",
"else",
":",
"return",
"0.0",
... | Compute Spline Basis
Evaluates the spline basis of order p defined by knots
at knot i and point u. | [
"Compute",
"Spline",
"Basis",
"Evaluates",
"the",
"spline",
"basis",
"of",
"order",
"p",
"defined",
"by",
"knots",
"at",
"knot",
"i",
"and",
"point",
"u",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L322-L344 |
nwilming/ocupy | ocupy/measures.py | prediction_scores | def prediction_scores(prediction, fm, **kw):
"""
Evaluates a prediction against fixations in a fixmat with different measures.
The default measures which are used are AUC, NSS and KL-divergence. This
can be changed by setting the list of measures with set_scores.
As different measures need potentia... | python | def prediction_scores(prediction, fm, **kw):
"""
Evaluates a prediction against fixations in a fixmat with different measures.
The default measures which are used are AUC, NSS and KL-divergence. This
can be changed by setting the list of measures with set_scores.
As different measures need potentia... | [
"def",
"prediction_scores",
"(",
"prediction",
",",
"fm",
",",
"*",
"*",
"kw",
")",
":",
"if",
"prediction",
"==",
"None",
":",
"return",
"[",
"np",
".",
"NaN",
"for",
"measure",
"in",
"scores",
"]",
"results",
"=",
"[",
"]",
"for",
"measure",
"in",
... | Evaluates a prediction against fixations in a fixmat with different measures.
The default measures which are used are AUC, NSS and KL-divergence. This
can be changed by setting the list of measures with set_scores.
As different measures need potentially different parameters, the kw
dictionary can be us... | [
"Evaluates",
"a",
"prediction",
"against",
"fixations",
"in",
"a",
"fixmat",
"with",
"different",
"measures",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L23-L64 |
nwilming/ocupy | ocupy/measures.py | kldiv_model | def kldiv_model(prediction, fm):
"""
wraps kldiv functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Should be filtered for the image corresponding to the prediction
"""
(_, r_x) = calc_resize_factor(prediction, ... | python | def kldiv_model(prediction, fm):
"""
wraps kldiv functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Should be filtered for the image corresponding to the prediction
"""
(_, r_x) = calc_resize_factor(prediction, ... | [
"def",
"kldiv_model",
"(",
"prediction",
",",
"fm",
")",
":",
"(",
"_",
",",
"r_x",
")",
"=",
"calc_resize_factor",
"(",
"prediction",
",",
"fm",
".",
"image_size",
")",
"q",
"=",
"np",
".",
"array",
"(",
"prediction",
",",
"copy",
"=",
"True",
")",
... | wraps kldiv functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Should be filtered for the image corresponding to the prediction | [
"wraps",
"kldiv",
"functionality",
"for",
"model",
"evaluation"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L80-L94 |
nwilming/ocupy | ocupy/measures.py | kldiv | def kldiv(p, q, distp = None, distq = None, scale_factor = 1):
"""
Computes the Kullback-Leibler divergence between two distributions.
Parameters
p : Matrix
The first probability distribution
q : Matrix
The second probability distribution
distp : fixmat
... | python | def kldiv(p, q, distp = None, distq = None, scale_factor = 1):
"""
Computes the Kullback-Leibler divergence between two distributions.
Parameters
p : Matrix
The first probability distribution
q : Matrix
The second probability distribution
distp : fixmat
... | [
"def",
"kldiv",
"(",
"p",
",",
"q",
",",
"distp",
"=",
"None",
",",
"distq",
"=",
"None",
",",
"scale_factor",
"=",
"1",
")",
":",
"assert",
"q",
"!=",
"None",
"or",
"distq",
"!=",
"None",
",",
"\"Either q or distq have to be given\"",
"assert",
"p",
"... | Computes the Kullback-Leibler divergence between two distributions.
Parameters
p : Matrix
The first probability distribution
q : Matrix
The second probability distribution
distp : fixmat
If p is None, distp is used to compute a FDM which
is th... | [
"Computes",
"the",
"Kullback",
"-",
"Leibler",
"divergence",
"between",
"two",
"distributions",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L96-L129 |
nwilming/ocupy | ocupy/measures.py | kldiv_cs_model | def kldiv_cs_model(prediction, fm):
"""
Computes Chao-Shen corrected KL-divergence between prediction
and fdm made from fixations in fm.
Parameters :
prediction : np.ndarray
a fixation density map
fm : FixMat object
"""
# compute histogram of fixations needed for Cha... | python | def kldiv_cs_model(prediction, fm):
"""
Computes Chao-Shen corrected KL-divergence between prediction
and fdm made from fixations in fm.
Parameters :
prediction : np.ndarray
a fixation density map
fm : FixMat object
"""
# compute histogram of fixations needed for Cha... | [
"def",
"kldiv_cs_model",
"(",
"prediction",
",",
"fm",
")",
":",
"# compute histogram of fixations needed for ChaoShen corrected kl-div",
"# image category must exist (>-1) and image_size must be non-empty",
"assert",
"(",
"len",
"(",
"fm",
".",
"image_size",
")",
"==",
"2",
... | Computes Chao-Shen corrected KL-divergence between prediction
and fdm made from fixations in fm.
Parameters :
prediction : np.ndarray
a fixation density map
fm : FixMat object | [
"Computes",
"Chao",
"-",
"Shen",
"corrected",
"KL",
"-",
"divergence",
"between",
"prediction",
"and",
"fdm",
"made",
"from",
"fixations",
"in",
"fm",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L131-L164 |
nwilming/ocupy | ocupy/measures.py | chao_shen | def chao_shen(q):
"""
Computes some terms needed for the Chao-Shen KL correction.
"""
yx = q[q > 0] # remove bins with zero counts
n = np.sum(yx)
p = yx.astype(float)/n
f1 = np.sum(yx == 1) # number of singletons in the sample
if f1 == n: # avoid C == 0
f1 -= 1
C = 1 - (f1/n)... | python | def chao_shen(q):
"""
Computes some terms needed for the Chao-Shen KL correction.
"""
yx = q[q > 0] # remove bins with zero counts
n = np.sum(yx)
p = yx.astype(float)/n
f1 = np.sum(yx == 1) # number of singletons in the sample
if f1 == n: # avoid C == 0
f1 -= 1
C = 1 - (f1/n)... | [
"def",
"chao_shen",
"(",
"q",
")",
":",
"yx",
"=",
"q",
"[",
"q",
">",
"0",
"]",
"# remove bins with zero counts",
"n",
"=",
"np",
".",
"sum",
"(",
"yx",
")",
"p",
"=",
"yx",
".",
"astype",
"(",
"float",
")",
"/",
"n",
"f1",
"=",
"np",
".",
"... | Computes some terms needed for the Chao-Shen KL correction. | [
"Computes",
"some",
"terms",
"needed",
"for",
"the",
"Chao",
"-",
"Shen",
"KL",
"correction",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L167-L181 |
nwilming/ocupy | ocupy/measures.py | correlation_model | def correlation_model(prediction, fm):
"""
wraps numpy.corrcoef functionality for model evaluation
input:
prediction: 2D Matrix
the model salience map
fm: fixmat
Used to compute a FDM to which the prediction is compared.
"""
(_, r_x) = calc_resize_factor(pred... | python | def correlation_model(prediction, fm):
"""
wraps numpy.corrcoef functionality for model evaluation
input:
prediction: 2D Matrix
the model salience map
fm: fixmat
Used to compute a FDM to which the prediction is compared.
"""
(_, r_x) = calc_resize_factor(pred... | [
"def",
"correlation_model",
"(",
"prediction",
",",
"fm",
")",
":",
"(",
"_",
",",
"r_x",
")",
"=",
"calc_resize_factor",
"(",
"prediction",
",",
"fm",
".",
"image_size",
")",
"fdm",
"=",
"compute_fdm",
"(",
"fm",
",",
"scale_factor",
"=",
"r_x",
")",
... | wraps numpy.corrcoef functionality for model evaluation
input:
prediction: 2D Matrix
the model salience map
fm: fixmat
Used to compute a FDM to which the prediction is compared. | [
"wraps",
"numpy",
".",
"corrcoef",
"functionality",
"for",
"model",
"evaluation"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L184-L196 |
nwilming/ocupy | ocupy/measures.py | nss_model | def nss_model(prediction, fm):
"""
wraps nss functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Fixations that define the actuals
"""
(r_y, r_x) = calc_resize_factor(prediction, fm.image_size)
fix = ((np.arr... | python | def nss_model(prediction, fm):
"""
wraps nss functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Fixations that define the actuals
"""
(r_y, r_x) = calc_resize_factor(prediction, fm.image_size)
fix = ((np.arr... | [
"def",
"nss_model",
"(",
"prediction",
",",
"fm",
")",
":",
"(",
"r_y",
",",
"r_x",
")",
"=",
"calc_resize_factor",
"(",
"prediction",
",",
"fm",
".",
"image_size",
")",
"fix",
"=",
"(",
"(",
"np",
".",
"array",
"(",
"fm",
".",
"y",
"-",
"1",
")"... | wraps nss functionality for model evaluation
input:
prediction: 2D matrix
the model salience map
fm : fixmat
Fixations that define the actuals | [
"wraps",
"nss",
"functionality",
"for",
"model",
"evaluation"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L199-L212 |
nwilming/ocupy | ocupy/measures.py | nss | def nss(prediction, fix):
"""
Compute the normalized scanpath salience
input:
fix : list, l[0] contains y, l[1] contains x
"""
prediction = prediction - np.mean(prediction)
prediction = prediction / np.std(prediction)
return np.mean(prediction[fix[0], fix[1]]) | python | def nss(prediction, fix):
"""
Compute the normalized scanpath salience
input:
fix : list, l[0] contains y, l[1] contains x
"""
prediction = prediction - np.mean(prediction)
prediction = prediction / np.std(prediction)
return np.mean(prediction[fix[0], fix[1]]) | [
"def",
"nss",
"(",
"prediction",
",",
"fix",
")",
":",
"prediction",
"=",
"prediction",
"-",
"np",
".",
"mean",
"(",
"prediction",
")",
"prediction",
"=",
"prediction",
"/",
"np",
".",
"std",
"(",
"prediction",
")",
"return",
"np",
".",
"mean",
"(",
... | Compute the normalized scanpath salience
input:
fix : list, l[0] contains y, l[1] contains x | [
"Compute",
"the",
"normalized",
"scanpath",
"salience"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L215-L225 |
nwilming/ocupy | ocupy/measures.py | roc_model | def roc_model(prediction, fm, ctr_loc = None, ctr_size = None):
"""
wraps roc functionality for model evaluation
Parameters:
prediction: 2D array
the model salience map
fm : fixmat
Fixations that define locations of the actuals
ctr_loc : tuple of (y.x) coordi... | python | def roc_model(prediction, fm, ctr_loc = None, ctr_size = None):
"""
wraps roc functionality for model evaluation
Parameters:
prediction: 2D array
the model salience map
fm : fixmat
Fixations that define locations of the actuals
ctr_loc : tuple of (y.x) coordi... | [
"def",
"roc_model",
"(",
"prediction",
",",
"fm",
",",
"ctr_loc",
"=",
"None",
",",
"ctr_size",
"=",
"None",
")",
":",
"# check if prediction is a valid numpy array",
"assert",
"type",
"(",
"prediction",
")",
"==",
"np",
".",
"ndarray",
"# check whether scaling pr... | wraps roc functionality for model evaluation
Parameters:
prediction: 2D array
the model salience map
fm : fixmat
Fixations that define locations of the actuals
ctr_loc : tuple of (y.x) coordinates, optional
Allows to specify control points for spatial
... | [
"wraps",
"roc",
"functionality",
"for",
"model",
"evaluation"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L228-L266 |
nwilming/ocupy | ocupy/measures.py | fast_roc | def fast_roc(actuals, controls):
"""
approximates the area under the roc curve for sets of actuals and controls.
Uses all values appearing in actuals as thresholds and lower sum
interpolation. Also returns arrays of the true positive rate and the false
positive rate that can be used for plotting the... | python | def fast_roc(actuals, controls):
"""
approximates the area under the roc curve for sets of actuals and controls.
Uses all values appearing in actuals as thresholds and lower sum
interpolation. Also returns arrays of the true positive rate and the false
positive rate that can be used for plotting the... | [
"def",
"fast_roc",
"(",
"actuals",
",",
"controls",
")",
":",
"assert",
"(",
"type",
"(",
"actuals",
")",
"is",
"np",
".",
"ndarray",
")",
"assert",
"(",
"type",
"(",
"controls",
")",
"is",
"np",
".",
"ndarray",
")",
"actuals",
"=",
"np",
".",
"rav... | approximates the area under the roc curve for sets of actuals and controls.
Uses all values appearing in actuals as thresholds and lower sum
interpolation. Also returns arrays of the true positive rate and the false
positive rate that can be used for plotting the roc curve.
Parameters:
actuals ... | [
"approximates",
"the",
"area",
"under",
"the",
"roc",
"curve",
"for",
"sets",
"of",
"actuals",
"and",
"controls",
".",
"Uses",
"all",
"values",
"appearing",
"in",
"actuals",
"as",
"thresholds",
"and",
"lower",
"sum",
"interpolation",
".",
"Also",
"returns",
... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L269-L307 |
nwilming/ocupy | ocupy/measures.py | faster_roc | def faster_roc(actuals, controls):
"""
Histogram based implementation of AUC unde ROC curve.
Parameters:
actuals : list
A list of numeric values for positive observations.
controls : list
A list of numeric values for negative observations.
"""
assert(type(actu... | python | def faster_roc(actuals, controls):
"""
Histogram based implementation of AUC unde ROC curve.
Parameters:
actuals : list
A list of numeric values for positive observations.
controls : list
A list of numeric values for negative observations.
"""
assert(type(actu... | [
"def",
"faster_roc",
"(",
"actuals",
",",
"controls",
")",
":",
"assert",
"(",
"type",
"(",
"actuals",
")",
"is",
"np",
".",
"ndarray",
")",
"assert",
"(",
"type",
"(",
"controls",
")",
"is",
"np",
".",
"ndarray",
")",
"if",
"len",
"(",
"actuals",
... | Histogram based implementation of AUC unde ROC curve.
Parameters:
actuals : list
A list of numeric values for positive observations.
controls : list
A list of numeric values for negative observations. | [
"Histogram",
"based",
"implementation",
"of",
"AUC",
"unde",
"ROC",
"curve",
".",
"Parameters",
":",
"actuals",
":",
"list",
"A",
"list",
"of",
"numeric",
"values",
"for",
"positive",
"observations",
".",
"controls",
":",
"list",
"A",
"list",
"of",
"numeric"... | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L309-L351 |
nwilming/ocupy | ocupy/measures.py | emd_model | def emd_model(prediction, fm):
"""
wraps emd functionality for model evaluation
requires:
OpenCV python bindings
input:
prediction: the model salience map
fm : fixmat filtered for the image corresponding to the prediction
"""
(_, r_x) = calc_resize_factor(prediction, fm... | python | def emd_model(prediction, fm):
"""
wraps emd functionality for model evaluation
requires:
OpenCV python bindings
input:
prediction: the model salience map
fm : fixmat filtered for the image corresponding to the prediction
"""
(_, r_x) = calc_resize_factor(prediction, fm... | [
"def",
"emd_model",
"(",
"prediction",
",",
"fm",
")",
":",
"(",
"_",
",",
"r_x",
")",
"=",
"calc_resize_factor",
"(",
"prediction",
",",
"fm",
".",
"image_size",
")",
"gt",
"=",
"fixmat",
".",
"compute_fdm",
"(",
"fm",
",",
"scale_factor",
"=",
"r_x",... | wraps emd functionality for model evaluation
requires:
OpenCV python bindings
input:
prediction: the model salience map
fm : fixmat filtered for the image corresponding to the prediction | [
"wraps",
"emd",
"functionality",
"for",
"model",
"evaluation"
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L382-L395 |
nwilming/ocupy | ocupy/measures.py | emd | def emd(prediction, ground_truth):
"""
Compute the Eart Movers Distance between prediction and model.
This implementation uses opencv for doing the actual work.
Unfortunately, at the time of implementation only the SWIG
bindings werer available and the numpy arrays have to
converted by hand. Th... | python | def emd(prediction, ground_truth):
"""
Compute the Eart Movers Distance between prediction and model.
This implementation uses opencv for doing the actual work.
Unfortunately, at the time of implementation only the SWIG
bindings werer available and the numpy arrays have to
converted by hand. Th... | [
"def",
"emd",
"(",
"prediction",
",",
"ground_truth",
")",
":",
"import",
"opencv",
"if",
"not",
"(",
"prediction",
".",
"shape",
"==",
"ground_truth",
".",
"shape",
")",
":",
"raise",
"RuntimeError",
"(",
"'Shapes of prediction and ground truth have'",
"+",
"' ... | Compute the Eart Movers Distance between prediction and model.
This implementation uses opencv for doing the actual work.
Unfortunately, at the time of implementation only the SWIG
bindings werer available and the numpy arrays have to
converted by hand. This changes with opencv 2.1. | [
"Compute",
"the",
"Eart",
"Movers",
"Distance",
"between",
"prediction",
"and",
"model",
"."
] | train | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/measures.py#L398-L423 |
kurtmckee/listparser | listparser/dates.py | _rfc822 | def _rfc822(date):
"""Parse RFC 822 dates and times
http://tools.ietf.org/html/rfc822#section-5
There are some formatting differences that are accounted for:
1. Years may be two or four digits.
2. The month and day can be swapped.
3. Additional timezone names are supported.
4. A default tim... | python | def _rfc822(date):
"""Parse RFC 822 dates and times
http://tools.ietf.org/html/rfc822#section-5
There are some formatting differences that are accounted for:
1. Years may be two or four digits.
2. The month and day can be swapped.
3. Additional timezone names are supported.
4. A default tim... | [
"def",
"_rfc822",
"(",
"date",
")",
":",
"daynames",
"=",
"set",
"(",
"[",
"'mon'",
",",
"'tue'",
",",
"'wed'",
",",
"'thu'",
",",
"'fri'",
",",
"'sat'",
",",
"'sun'",
"]",
")",
"months",
"=",
"{",
"'jan'",
":",
"1",
",",
"'feb'",
":",
"2",
","... | Parse RFC 822 dates and times
http://tools.ietf.org/html/rfc822#section-5
There are some formatting differences that are accounted for:
1. Years may be two or four digits.
2. The month and day can be swapped.
3. Additional timezone names are supported.
4. A default time and timezone are assumed... | [
"Parse",
"RFC",
"822",
"dates",
"and",
"times",
"http",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc822#section",
"-",
"5"
] | train | https://github.com/kurtmckee/listparser/blob/f9bc310a0ce567cd0611fea68be99974021f53c7/listparser/dates.py#L25-L126 |
kurtmckee/listparser | listparser/dates.py | _to_rfc822 | def _to_rfc822(date):
"""_to_rfc822(datetime.datetime) -> str
The datetime `strftime` method is subject to locale-specific
day and month names, so this function hardcodes the conversion."""
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
da... | python | def _to_rfc822(date):
"""_to_rfc822(datetime.datetime) -> str
The datetime `strftime` method is subject to locale-specific
day and month names, so this function hardcodes the conversion."""
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
da... | [
"def",
"_to_rfc822",
"(",
"date",
")",
":",
"months",
"=",
"[",
"'Jan'",
",",
"'Feb'",
",",
"'Mar'",
",",
"'Apr'",
",",
"'May'",
",",
"'Jun'",
",",
"'Jul'",
",",
"'Aug'",
",",
"'Sep'",
",",
"'Oct'",
",",
"'Nov'",
",",
"'Dec'",
"]",
"days",
"=",
"... | _to_rfc822(datetime.datetime) -> str
The datetime `strftime` method is subject to locale-specific
day and month names, so this function hardcodes the conversion. | [
"_to_rfc822",
"(",
"datetime",
".",
"datetime",
")",
"-",
">",
"str",
"The",
"datetime",
"strftime",
"method",
"is",
"subject",
"to",
"locale",
"-",
"specific",
"day",
"and",
"month",
"names",
"so",
"this",
"function",
"hardcodes",
"the",
"conversion",
"."
] | train | https://github.com/kurtmckee/listparser/blob/f9bc310a0ce567cd0611fea68be99974021f53c7/listparser/dates.py#L129-L145 |
cpburnz/python-sql-parameters | sqlparams/__init__.py | SQLParams.format | def format(self, sql, params):
"""
Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
simply a |sequence| of values ... | python | def format(self, sql, params):
"""
Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
simply a |sequence| of values ... | [
"def",
"format",
"(",
"self",
",",
"sql",
",",
"params",
")",
":",
"if",
"isinstance",
"(",
"sql",
",",
"unicode",
")",
":",
"string_type",
"=",
"unicode",
"elif",
"isinstance",
"(",
"sql",
",",
"bytes",
")",
":",
"string_type",
"=",
"bytes",
"sql",
... | Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
simply a |sequence| of values mapped by index.
Returns a 2-|tuple|... | [
"Formats",
"the",
"SQL",
"query",
"to",
"use",
"ordinal",
"parameters",
"instead",
"of",
"named",
"parameters",
"."
] | train | https://github.com/cpburnz/python-sql-parameters/blob/828088a54b84aa904ec54c50af60f8aecc62a5f4/sqlparams/__init__.py#L245-L301 |
cpburnz/python-sql-parameters | sqlparams/__init__.py | SQLParams.formatmany | def formatmany(self, sql, many_params):
"""
Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*many_params* (|iterable|) contains each *params* to format.
- *params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |se... | python | def formatmany(self, sql, many_params):
"""
Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*many_params* (|iterable|) contains each *params* to format.
- *params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |se... | [
"def",
"formatmany",
"(",
"self",
",",
"sql",
",",
"many_params",
")",
":",
"if",
"isinstance",
"(",
"sql",
",",
"unicode",
")",
":",
"string_type",
"=",
"unicode",
"elif",
"isinstance",
"(",
"sql",
",",
"bytes",
")",
":",
"string_type",
"=",
"bytes",
... | Formats the SQL query to use ordinal parameters instead of named
parameters.
*sql* (|string|) is the SQL query.
*many_params* (|iterable|) contains each *params* to format.
- *params* (|dict|) maps each named parameter (|string|) to value
(|object|). If |self.named| is "numeric", then *params* can be
... | [
"Formats",
"the",
"SQL",
"query",
"to",
"use",
"ordinal",
"parameters",
"instead",
"of",
"named",
"parameters",
"."
] | train | https://github.com/cpburnz/python-sql-parameters/blob/828088a54b84aa904ec54c50af60f8aecc62a5f4/sqlparams/__init__.py#L303-L386 |
hecrj/reticular | reticular.py | _get_parser | def _get_parser(f):
"""
Gets the parser for the command f, if it not exists it creates a new one
"""
_COMMAND_GROUPS[f.__module__].load()
if f.__name__ not in _COMMAND_GROUPS[f.__module__].parsers:
parser = _COMMAND_GROUPS[f.__module__].parser_generator.add_parser(f.__name__, help=f.__doc__... | python | def _get_parser(f):
"""
Gets the parser for the command f, if it not exists it creates a new one
"""
_COMMAND_GROUPS[f.__module__].load()
if f.__name__ not in _COMMAND_GROUPS[f.__module__].parsers:
parser = _COMMAND_GROUPS[f.__module__].parser_generator.add_parser(f.__name__, help=f.__doc__... | [
"def",
"_get_parser",
"(",
"f",
")",
":",
"_COMMAND_GROUPS",
"[",
"f",
".",
"__module__",
"]",
".",
"load",
"(",
")",
"if",
"f",
".",
"__name__",
"not",
"in",
"_COMMAND_GROUPS",
"[",
"f",
".",
"__module__",
"]",
".",
"parsers",
":",
"parser",
"=",
"_... | Gets the parser for the command f, if it not exists it creates a new one | [
"Gets",
"the",
"parser",
"for",
"the",
"command",
"f",
"if",
"it",
"not",
"exists",
"it",
"creates",
"a",
"new",
"one"
] | train | https://github.com/hecrj/reticular/blob/b83c632459b3215284124373931fcaef76bc64e8/reticular.py#L180-L193 |
bear/ronkyuu | ronkyuu/webmention.py | findMentions | def findMentions(sourceURL, targetURL=None, exclude_domains=[], content=None, test_urls=True, headers={}, timeout=None):
"""Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
If an... | python | def findMentions(sourceURL, targetURL=None, exclude_domains=[], content=None, test_urls=True, headers={}, timeout=None):
"""Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
If an... | [
"def",
"findMentions",
"(",
"sourceURL",
",",
"targetURL",
"=",
"None",
",",
"exclude_domains",
"=",
"[",
"]",
",",
"content",
"=",
"None",
",",
"test_urls",
"=",
"True",
",",
"headers",
"=",
"{",
"}",
",",
"timeout",
"=",
"None",
")",
":",
"__doc__",
... | Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
If any have an href attribute that is not from the
one of the items in exclude_domains, append it to our lists.
:param sourc... | [
"Find",
"all",
"<a",
"/",
">",
"elements",
"in",
"the",
"given",
"html",
"for",
"a",
"post",
".",
"Only",
"scan",
"html",
"element",
"matching",
"all",
"criteria",
"in",
"look_in",
"."
] | train | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/webmention.py#L41-L112 |
bear/ronkyuu | ronkyuu/webmention.py | findEndpoint | def findEndpoint(html):
"""Search the given html content for all <link /> elements
and return any discovered WebMention URL.
:param html: html content
:rtype: WebMention URL
"""
poss_rels = ['webmention', 'http://webmention.org', 'http://webmention.org/', 'https://webmention.org', 'https://webm... | python | def findEndpoint(html):
"""Search the given html content for all <link /> elements
and return any discovered WebMention URL.
:param html: html content
:rtype: WebMention URL
"""
poss_rels = ['webmention', 'http://webmention.org', 'http://webmention.org/', 'https://webmention.org', 'https://webm... | [
"def",
"findEndpoint",
"(",
"html",
")",
":",
"poss_rels",
"=",
"[",
"'webmention'",
",",
"'http://webmention.org'",
",",
"'http://webmention.org/'",
",",
"'https://webmention.org'",
",",
"'https://webmention.org/'",
"]",
"# find elements with correct rels and a href value",
... | Search the given html content for all <link /> elements
and return any discovered WebMention URL.
:param html: html content
:rtype: WebMention URL | [
"Search",
"the",
"given",
"html",
"content",
"for",
"all",
"<link",
"/",
">",
"elements",
"and",
"return",
"any",
"discovered",
"WebMention",
"URL",
"."
] | train | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/webmention.py#L115-L131 |
bear/ronkyuu | ronkyuu/webmention.py | discoverEndpoint | def discoverEndpoint(url, test_urls=True, headers={}, timeout=None, request=None, debug=False):
"""Discover any WebMention endpoint for a given URL.
:param link: URL to discover WebMention endpoint
:param test_urls: optional flag to test URLs for validation
:param headers: optional headers to send with... | python | def discoverEndpoint(url, test_urls=True, headers={}, timeout=None, request=None, debug=False):
"""Discover any WebMention endpoint for a given URL.
:param link: URL to discover WebMention endpoint
:param test_urls: optional flag to test URLs for validation
:param headers: optional headers to send with... | [
"def",
"discoverEndpoint",
"(",
"url",
",",
"test_urls",
"=",
"True",
",",
"headers",
"=",
"{",
"}",
",",
"timeout",
"=",
"None",
",",
"request",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"if",
"test_urls",
":",
"URLValidator",
"(",
"message",... | Discover any WebMention endpoint for a given URL.
:param link: URL to discover WebMention endpoint
:param test_urls: optional flag to test URLs for validation
:param headers: optional headers to send with any web requests
:type headers dict
:param timeout: optional timeout for web requests
:typ... | [
"Discover",
"any",
"WebMention",
"endpoint",
"for",
"a",
"given",
"URL",
"."
] | train | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/webmention.py#L134-L185 |
bear/ronkyuu | ronkyuu/webmention.py | sendWebmention | def sendWebmention(sourceURL, targetURL, webmention=None, test_urls=True, vouchDomain=None,
headers={}, timeout=None, debug=False):
"""Send to the :targetURL: a WebMention for the :sourceURL:
The WebMention will be discovered if not given in the :webmention:
parameter.
:param source... | python | def sendWebmention(sourceURL, targetURL, webmention=None, test_urls=True, vouchDomain=None,
headers={}, timeout=None, debug=False):
"""Send to the :targetURL: a WebMention for the :sourceURL:
The WebMention will be discovered if not given in the :webmention:
parameter.
:param source... | [
"def",
"sendWebmention",
"(",
"sourceURL",
",",
"targetURL",
",",
"webmention",
"=",
"None",
",",
"test_urls",
"=",
"True",
",",
"vouchDomain",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
",",
"timeout",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":... | Send to the :targetURL: a WebMention for the :sourceURL:
The WebMention will be discovered if not given in the :webmention:
parameter.
:param sourceURL: URL that is referencing :targetURL:
:param targetURL: URL of mentioned post
:param webmention: optional WebMention endpoint
:param test_urls:... | [
"Send",
"to",
"the",
":",
"targetURL",
":",
"a",
"WebMention",
"for",
"the",
":",
"sourceURL",
":"
] | train | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/webmention.py#L187-L249 |
bear/ronkyuu | ronkyuu/tools.py | parse_link_header | def parse_link_header(link):
"""takes the link header as a string and returns a dictionary with rel values as keys and urls as values
:param link: link header as a string
:rtype: dictionary {rel_name: rel_value}
"""
rel_dict = {}
for rels in link.split(','):
rel_break = quoted_split(rels... | python | def parse_link_header(link):
"""takes the link header as a string and returns a dictionary with rel values as keys and urls as values
:param link: link header as a string
:rtype: dictionary {rel_name: rel_value}
"""
rel_dict = {}
for rels in link.split(','):
rel_break = quoted_split(rels... | [
"def",
"parse_link_header",
"(",
"link",
")",
":",
"rel_dict",
"=",
"{",
"}",
"for",
"rels",
"in",
"link",
".",
"split",
"(",
"','",
")",
":",
"rel_break",
"=",
"quoted_split",
"(",
"rels",
",",
"';'",
")",
"try",
":",
"rel_url",
"=",
"re",
".",
"s... | takes the link header as a string and returns a dictionary with rel values as keys and urls as values
:param link: link header as a string
:rtype: dictionary {rel_name: rel_value} | [
"takes",
"the",
"link",
"header",
"as",
"a",
"string",
"and",
"returns",
"a",
"dictionary",
"with",
"rel",
"values",
"as",
"keys",
"and",
"urls",
"as",
"values",
":",
"param",
"link",
":",
"link",
"header",
"as",
"a",
"string",
":",
"rtype",
":",
"dict... | train | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/tools.py#L86-L104 |
bear/ronkyuu | ronkyuu/relme.py | findRelMe | def findRelMe(sourceURL):
"""Find all <a /> elements in the given html for a post.
If any have an href attribute that is rel="me" then include
it in the result.
:param sourceURL: the URL for the post we are scanning
:rtype: dictionary of RelMe references
"""
r = requests.get(sourceURL)
... | python | def findRelMe(sourceURL):
"""Find all <a /> elements in the given html for a post.
If any have an href attribute that is rel="me" then include
it in the result.
:param sourceURL: the URL for the post we are scanning
:rtype: dictionary of RelMe references
"""
r = requests.get(sourceURL)
... | [
"def",
"findRelMe",
"(",
"sourceURL",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"sourceURL",
")",
"result",
"=",
"{",
"'status'",
":",
"r",
".",
"status_code",
",",
"'headers'",
":",
"r",
".",
"headers",
",",
"'history'",
":",
"r",
".",
"histo... | Find all <a /> elements in the given html for a post.
If any have an href attribute that is rel="me" then include
it in the result.
:param sourceURL: the URL for the post we are scanning
:rtype: dictionary of RelMe references | [
"Find",
"all",
"<a",
"/",
">",
"elements",
"in",
"the",
"given",
"html",
"for",
"a",
"post",
"."
] | train | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/relme.py#L63-L89 |
bear/ronkyuu | ronkyuu/relme.py | confirmRelMe | def confirmRelMe(profileURL, resourceURL, profileRelMes=None, resourceRelMes=None):
"""Determine if a given :resourceURL: is authoritative for the :profileURL:
TODO add https/http filtering for those who wish to limit/restrict urls to match fully
TODO add code to ensure that each item in the redirect chain... | python | def confirmRelMe(profileURL, resourceURL, profileRelMes=None, resourceRelMes=None):
"""Determine if a given :resourceURL: is authoritative for the :profileURL:
TODO add https/http filtering for those who wish to limit/restrict urls to match fully
TODO add code to ensure that each item in the redirect chain... | [
"def",
"confirmRelMe",
"(",
"profileURL",
",",
"resourceURL",
",",
"profileRelMes",
"=",
"None",
",",
"resourceRelMes",
"=",
"None",
")",
":",
"result",
"=",
"False",
"profile",
"=",
"normalizeURL",
"(",
"profileURL",
")",
"if",
"profileRelMes",
"is",
"None",
... | Determine if a given :resourceURL: is authoritative for the :profileURL:
TODO add https/http filtering for those who wish to limit/restrict urls to match fully
TODO add code to ensure that each item in the redirect chain is authoritative
:param profileURL: URL of the user
:param resourceURL: URL of th... | [
"Determine",
"if",
"a",
"given",
":",
"resourceURL",
":",
"is",
"authoritative",
"for",
"the",
":",
"profileURL",
":"
] | train | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/relme.py#L92-L119 |
alexras/bread | bread/utils.py | indent_text | def indent_text(string, indent_level=2):
"""Indent every line of text in a newline-delimited string"""
indented_lines = []
indent_spaces = ' ' * indent_level
for line in string.split('\n'):
indented_lines.append(indent_spaces + line)
return '\n'.join(indented_lines) | python | def indent_text(string, indent_level=2):
"""Indent every line of text in a newline-delimited string"""
indented_lines = []
indent_spaces = ' ' * indent_level
for line in string.split('\n'):
indented_lines.append(indent_spaces + line)
return '\n'.join(indented_lines) | [
"def",
"indent_text",
"(",
"string",
",",
"indent_level",
"=",
"2",
")",
":",
"indented_lines",
"=",
"[",
"]",
"indent_spaces",
"=",
"' '",
"*",
"indent_level",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
":",
"indented_lines",
".",
"... | Indent every line of text in a newline-delimited string | [
"Indent",
"every",
"line",
"of",
"text",
"in",
"a",
"newline",
"-",
"delimited",
"string"
] | train | https://github.com/alexras/bread/blob/2e131380878c07500167fc12685e7bff1df258a4/bread/utils.py#L1-L10 |
takluyver/requests_download | requests_download.py | download | def download(url, target, headers=None, trackers=()):
"""Download a file using requests.
This is like urllib.request.urlretrieve, but:
- requests validates SSL certificates by default
- you can pass tracker objects to e.g. display a progress bar or calculate
a file hash.
"""
if headers i... | python | def download(url, target, headers=None, trackers=()):
"""Download a file using requests.
This is like urllib.request.urlretrieve, but:
- requests validates SSL certificates by default
- you can pass tracker objects to e.g. display a progress bar or calculate
a file hash.
"""
if headers i... | [
"def",
"download",
"(",
"url",
",",
"target",
",",
"headers",
"=",
"None",
",",
"trackers",
"=",
"(",
")",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"headers",
".",
"setdefault",
"(",
"'user-agent'",
",",
"'requests_downlo... | Download a file using requests.
This is like urllib.request.urlretrieve, but:
- requests validates SSL certificates by default
- you can pass tracker objects to e.g. display a progress bar or calculate
a file hash. | [
"Download",
"a",
"file",
"using",
"requests",
"."
] | train | https://github.com/takluyver/requests_download/blob/bc0412bb930051af21ab1959402abab883c78e76/requests_download.py#L65-L91 |
alexras/bread | bread/lifecycle.py | write | def write(parsed_obj, spec=None, filename=None):
"""Writes an object created by `parse` to either a file or a bytearray.
If the object doesn't end on a byte boundary, zeroes are appended to it
until it does.
"""
if not isinstance(parsed_obj, BreadStruct):
raise ValueError(
'Obje... | python | def write(parsed_obj, spec=None, filename=None):
"""Writes an object created by `parse` to either a file or a bytearray.
If the object doesn't end on a byte boundary, zeroes are appended to it
until it does.
"""
if not isinstance(parsed_obj, BreadStruct):
raise ValueError(
'Obje... | [
"def",
"write",
"(",
"parsed_obj",
",",
"spec",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"parsed_obj",
",",
"BreadStruct",
")",
":",
"raise",
"ValueError",
"(",
"'Object to write must be a structure created '",
"'by br... | Writes an object created by `parse` to either a file or a bytearray.
If the object doesn't end on a byte boundary, zeroes are appended to it
until it does. | [
"Writes",
"an",
"object",
"created",
"by",
"parse",
"to",
"either",
"a",
"file",
"or",
"a",
"bytearray",
"."
] | train | https://github.com/alexras/bread/blob/2e131380878c07500167fc12685e7bff1df258a4/bread/lifecycle.py#L41-L56 |
audreyr/alotofeffort | alotofeffort/send.py | deploy_file | def deploy_file(file_path, bucket):
""" Uploads a file to an S3 bucket, as a public file. """
# Paths look like:
# index.html
# css/bootstrap.min.css
logger.info("Deploying {0}".format(file_path))
# Upload the actual file to file_path
k = Key(bucket)
k.key = file_path
try:
... | python | def deploy_file(file_path, bucket):
""" Uploads a file to an S3 bucket, as a public file. """
# Paths look like:
# index.html
# css/bootstrap.min.css
logger.info("Deploying {0}".format(file_path))
# Upload the actual file to file_path
k = Key(bucket)
k.key = file_path
try:
... | [
"def",
"deploy_file",
"(",
"file_path",
",",
"bucket",
")",
":",
"# Paths look like:",
"# index.html",
"# css/bootstrap.min.css",
"logger",
".",
"info",
"(",
"\"Deploying {0}\"",
".",
"format",
"(",
"file_path",
")",
")",
"# Upload the actual file to file_path",
"k",
... | Uploads a file to an S3 bucket, as a public file. | [
"Uploads",
"a",
"file",
"to",
"an",
"S3",
"bucket",
"as",
"a",
"public",
"file",
"."
] | train | https://github.com/audreyr/alotofeffort/blob/06deca82a70fa9896496fd44c8c6f24707396c50/alotofeffort/send.py#L15-L35 |
audreyr/alotofeffort | alotofeffort/send.py | deploy | def deploy(www_dir, bucket_name):
""" Deploy to the configured S3 bucket. """
# Set up the connection to an S3 bucket.
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
# Deploy each changed file in www_dir
os.chdir(www_dir)
for root, dirs, files in os.walk('.'):
for f... | python | def deploy(www_dir, bucket_name):
""" Deploy to the configured S3 bucket. """
# Set up the connection to an S3 bucket.
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
# Deploy each changed file in www_dir
os.chdir(www_dir)
for root, dirs, files in os.walk('.'):
for f... | [
"def",
"deploy",
"(",
"www_dir",
",",
"bucket_name",
")",
":",
"# Set up the connection to an S3 bucket.",
"conn",
"=",
"boto",
".",
"connect_s3",
"(",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
"bucket_name",
")",
"# Deploy each changed file in www_dir",
"... | Deploy to the configured S3 bucket. | [
"Deploy",
"to",
"the",
"configured",
"S3",
"bucket",
"."
] | train | https://github.com/audreyr/alotofeffort/blob/06deca82a70fa9896496fd44c8c6f24707396c50/alotofeffort/send.py#L38-L67 |
audreyr/alotofeffort | alotofeffort/send.py | has_changed_since_last_deploy | def has_changed_since_last_deploy(file_path, bucket):
"""
Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:... | python | def has_changed_since_last_deploy(file_path, bucket):
"""
Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:... | [
"def",
"has_changed_since_last_deploy",
"(",
"file_path",
",",
"bucket",
")",
":",
"msg",
"=",
"\"Checking if {0} has changed since last deploy.\"",
".",
"format",
"(",
"file_path",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"with",
"open",
"(",
"file_path",
")... | Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:returns: True if the file has changed, else False. | [
"Checks",
"if",
"a",
"file",
"has",
"changed",
"since",
"the",
"last",
"time",
"it",
"was",
"deployed",
"."
] | train | https://github.com/audreyr/alotofeffort/blob/06deca82a70fa9896496fd44c8c6f24707396c50/alotofeffort/send.py#L70-L105 |
audreyr/alotofeffort | alotofeffort/main.py | main | def main():
""" Entry point for the package, as defined in setup.py. """
# Log info and above to console
logging.basicConfig(
format='%(levelname)s: %(message)s', level=logging.INFO)
# Get command line input/output arguments
msg = 'Instantly deploy static HTML sites to S3 at the command li... | python | def main():
""" Entry point for the package, as defined in setup.py. """
# Log info and above to console
logging.basicConfig(
format='%(levelname)s: %(message)s', level=logging.INFO)
# Get command line input/output arguments
msg = 'Instantly deploy static HTML sites to S3 at the command li... | [
"def",
"main",
"(",
")",
":",
"# Log info and above to console",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'%(levelname)s: %(message)s'",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
"# Get command line input/output arguments",
"msg",
"=",
"'Instantly deplo... | Entry point for the package, as defined in setup.py. | [
"Entry",
"point",
"for",
"the",
"package",
"as",
"defined",
"in",
"setup",
".",
"py",
"."
] | train | https://github.com/audreyr/alotofeffort/blob/06deca82a70fa9896496fd44c8c6f24707396c50/alotofeffort/main.py#L9-L30 |
rainmanwy/robotframework-SikuliLibrary | src/python/sikuli.py | SikuliLibrary.start_sikuli_process | def start_sikuli_process(self, port=None):
"""
This keyword is used to start sikuli java process.
If library is inited with mode "OLD", sikuli java process is started automatically.
If library is inited with mode "NEW", this keyword should be used.
:param port: port of sikuli ja... | python | def start_sikuli_process(self, port=None):
"""
This keyword is used to start sikuli java process.
If library is inited with mode "OLD", sikuli java process is started automatically.
If library is inited with mode "NEW", this keyword should be used.
:param port: port of sikuli ja... | [
"def",
"start_sikuli_process",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"if",
"port",
"is",
"None",
"or",
"int",
"(",
"port",
")",
"==",
"0",
":",
"port",
"=",
"self",
".",
"_get_free_tcp_port",
"(",
")",
"self",
".",
"port",
"=",
"port",
"... | This keyword is used to start sikuli java process.
If library is inited with mode "OLD", sikuli java process is started automatically.
If library is inited with mode "NEW", this keyword should be used.
:param port: port of sikuli java process, if value is None or 0, a random free port will be u... | [
"This",
"keyword",
"is",
"used",
"to",
"start",
"sikuli",
"java",
"process",
".",
"If",
"library",
"is",
"inited",
"with",
"mode",
"OLD",
"sikuli",
"java",
"process",
"is",
"started",
"automatically",
".",
"If",
"library",
"is",
"inited",
"with",
"mode",
"... | train | https://github.com/rainmanwy/robotframework-SikuliLibrary/blob/992874dd96b139246a62fb07ec763e0a4caffad8/src/python/sikuli.py#L65-L93 |
JamesRitchie/django-rest-framework-expiring-tokens | rest_framework_expiring_authtoken/views.py | ObtainExpiringAuthToken.post | def post(self, request):
"""Respond to POSTed username/password with token."""
serializer = AuthTokenSerializer(data=request.data)
if serializer.is_valid():
token, _ = ExpiringToken.objects.get_or_create(
user=serializer.validated_data['user']
)
... | python | def post(self, request):
"""Respond to POSTed username/password with token."""
serializer = AuthTokenSerializer(data=request.data)
if serializer.is_valid():
token, _ = ExpiringToken.objects.get_or_create(
user=serializer.validated_data['user']
)
... | [
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"serializer",
"=",
"AuthTokenSerializer",
"(",
"data",
"=",
"request",
".",
"data",
")",
"if",
"serializer",
".",
"is_valid",
"(",
")",
":",
"token",
",",
"_",
"=",
"ExpiringToken",
".",
"objects",
... | Respond to POSTed username/password with token. | [
"Respond",
"to",
"POSTed",
"username",
"/",
"password",
"with",
"token",
"."
] | train | https://github.com/JamesRitchie/django-rest-framework-expiring-tokens/blob/e62f1f92a621575174172e970da624d367ac0cf6/rest_framework_expiring_authtoken/views.py#L20-L39 |
JamesRitchie/django-rest-framework-expiring-tokens | rest_framework_expiring_authtoken/settings.py | TokenSettings.EXPIRING_TOKEN_LIFESPAN | def EXPIRING_TOKEN_LIFESPAN(self):
"""
Return the allowed lifespan of a token as a TimeDelta object.
Defaults to 30 days.
"""
try:
val = settings.EXPIRING_TOKEN_LIFESPAN
except AttributeError:
val = timedelta(days=30)
return val | python | def EXPIRING_TOKEN_LIFESPAN(self):
"""
Return the allowed lifespan of a token as a TimeDelta object.
Defaults to 30 days.
"""
try:
val = settings.EXPIRING_TOKEN_LIFESPAN
except AttributeError:
val = timedelta(days=30)
return val | [
"def",
"EXPIRING_TOKEN_LIFESPAN",
"(",
"self",
")",
":",
"try",
":",
"val",
"=",
"settings",
".",
"EXPIRING_TOKEN_LIFESPAN",
"except",
"AttributeError",
":",
"val",
"=",
"timedelta",
"(",
"days",
"=",
"30",
")",
"return",
"val"
] | Return the allowed lifespan of a token as a TimeDelta object.
Defaults to 30 days. | [
"Return",
"the",
"allowed",
"lifespan",
"of",
"a",
"token",
"as",
"a",
"TimeDelta",
"object",
"."
] | train | https://github.com/JamesRitchie/django-rest-framework-expiring-tokens/blob/e62f1f92a621575174172e970da624d367ac0cf6/rest_framework_expiring_authtoken/settings.py#L16-L27 |
JamesRitchie/django-rest-framework-expiring-tokens | rest_framework_expiring_authtoken/models.py | ExpiringToken.expired | def expired(self):
"""Return boolean indicating token expiration."""
now = timezone.now()
if self.created < now - token_settings.EXPIRING_TOKEN_LIFESPAN:
return True
return False | python | def expired(self):
"""Return boolean indicating token expiration."""
now = timezone.now()
if self.created < now - token_settings.EXPIRING_TOKEN_LIFESPAN:
return True
return False | [
"def",
"expired",
"(",
"self",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"self",
".",
"created",
"<",
"now",
"-",
"token_settings",
".",
"EXPIRING_TOKEN_LIFESPAN",
":",
"return",
"True",
"return",
"False"
] | Return boolean indicating token expiration. | [
"Return",
"boolean",
"indicating",
"token",
"expiration",
"."
] | train | https://github.com/JamesRitchie/django-rest-framework-expiring-tokens/blob/e62f1f92a621575174172e970da624d367ac0cf6/rest_framework_expiring_authtoken/models.py#L21-L26 |
commonsense/metanl | metanl/extprocess.py | unicode_is_punctuation | def unicode_is_punctuation(text):
"""
Test if a token is made entirely of Unicode characters of the following
classes:
- P: punctuation
- S: symbols
- Z: separators
- M: combining marks
- C: control characters
>>> unicode_is_punctuation('word')
False
>>> unicode_is_punctuat... | python | def unicode_is_punctuation(text):
"""
Test if a token is made entirely of Unicode characters of the following
classes:
- P: punctuation
- S: symbols
- Z: separators
- M: combining marks
- C: control characters
>>> unicode_is_punctuation('word')
False
>>> unicode_is_punctuat... | [
"def",
"unicode_is_punctuation",
"(",
"text",
")",
":",
"for",
"char",
"in",
"str_func",
"(",
"text",
")",
":",
"category",
"=",
"unicodedata",
".",
"category",
"(",
"char",
")",
"[",
"0",
"]",
"if",
"category",
"not",
"in",
"'PSZMC'",
":",
"return",
"... | Test if a token is made entirely of Unicode characters of the following
classes:
- P: punctuation
- S: symbols
- Z: separators
- M: combining marks
- C: control characters
>>> unicode_is_punctuation('word')
False
>>> unicode_is_punctuation('。')
True
>>> unicode_is_punctuati... | [
"Test",
"if",
"a",
"token",
"is",
"made",
"entirely",
"of",
"Unicode",
"characters",
"of",
"the",
"following",
"classes",
":"
] | train | https://github.com/commonsense/metanl/blob/4b9ae8353489cc409bebd7e1fe10ab5b527b078e/metanl/extprocess.py#L246-L272 |
commonsense/metanl | metanl/extprocess.py | ProcessWrapper.process | def process(self):
"""
Store the actual process in _process. If it doesn't exist yet, create
it.
"""
if hasattr(self, '_process'):
return self._process
else:
self._process = self._get_process()
return self._process | python | def process(self):
"""
Store the actual process in _process. If it doesn't exist yet, create
it.
"""
if hasattr(self, '_process'):
return self._process
else:
self._process = self._get_process()
return self._process | [
"def",
"process",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_process'",
")",
":",
"return",
"self",
".",
"_process",
"else",
":",
"self",
".",
"_process",
"=",
"self",
".",
"_get_process",
"(",
")",
"return",
"self",
".",
"_process"
] | Store the actual process in _process. If it doesn't exist yet, create
it. | [
"Store",
"the",
"actual",
"process",
"in",
"_process",
".",
"If",
"it",
"doesn",
"t",
"exist",
"yet",
"create",
"it",
"."
] | train | https://github.com/commonsense/metanl/blob/4b9ae8353489cc409bebd7e1fe10ab5b527b078e/metanl/extprocess.py#L52-L61 |
commonsense/metanl | metanl/extprocess.py | ProcessWrapper._get_process | def _get_process(self):
"""
Create the process by running the specified command.
"""
command = self._get_command()
return subprocess.Popen(command, bufsize=-1, close_fds=True,
stdout=subprocess.PIPE,
stdin=subprocess... | python | def _get_process(self):
"""
Create the process by running the specified command.
"""
command = self._get_command()
return subprocess.Popen(command, bufsize=-1, close_fds=True,
stdout=subprocess.PIPE,
stdin=subprocess... | [
"def",
"_get_process",
"(",
"self",
")",
":",
"command",
"=",
"self",
".",
"_get_command",
"(",
")",
"return",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"bufsize",
"=",
"-",
"1",
",",
"close_fds",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
"... | Create the process by running the specified command. | [
"Create",
"the",
"process",
"by",
"running",
"the",
"specified",
"command",
"."
] | train | https://github.com/commonsense/metanl/blob/4b9ae8353489cc409bebd7e1fe10ab5b527b078e/metanl/extprocess.py#L70-L77 |
commonsense/metanl | metanl/extprocess.py | ProcessWrapper.tokenize_list | def tokenize_list(self, text):
"""
Split a text into separate words.
"""
return [self.get_record_token(record) for record in self.analyze(text)] | python | def tokenize_list(self, text):
"""
Split a text into separate words.
"""
return [self.get_record_token(record) for record in self.analyze(text)] | [
"def",
"tokenize_list",
"(",
"self",
",",
"text",
")",
":",
"return",
"[",
"self",
".",
"get_record_token",
"(",
"record",
")",
"for",
"record",
"in",
"self",
".",
"analyze",
"(",
"text",
")",
"]"
] | Split a text into separate words. | [
"Split",
"a",
"text",
"into",
"separate",
"words",
"."
] | train | https://github.com/commonsense/metanl/blob/4b9ae8353489cc409bebd7e1fe10ab5b527b078e/metanl/extprocess.py#L117-L121 |
commonsense/metanl | metanl/extprocess.py | ProcessWrapper.is_stopword | def is_stopword(self, text):
"""
Determine whether a single word is a stopword, or whether a short
phrase is made entirely of stopwords, disregarding context.
Use of this function should be avoided; it's better to give the text
in context and let the process determine which word... | python | def is_stopword(self, text):
"""
Determine whether a single word is a stopword, or whether a short
phrase is made entirely of stopwords, disregarding context.
Use of this function should be avoided; it's better to give the text
in context and let the process determine which word... | [
"def",
"is_stopword",
"(",
"self",
",",
"text",
")",
":",
"found_content_word",
"=",
"False",
"for",
"record",
"in",
"self",
".",
"analyze",
"(",
"text",
")",
":",
"if",
"not",
"self",
".",
"is_stopword_record",
"(",
"record",
")",
":",
"found_content_word... | Determine whether a single word is a stopword, or whether a short
phrase is made entirely of stopwords, disregarding context.
Use of this function should be avoided; it's better to give the text
in context and let the process determine which words are the stopwords. | [
"Determine",
"whether",
"a",
"single",
"word",
"is",
"a",
"stopword",
"or",
"whether",
"a",
"short",
"phrase",
"is",
"made",
"entirely",
"of",
"stopwords",
"disregarding",
"context",
"."
] | train | https://github.com/commonsense/metanl/blob/4b9ae8353489cc409bebd7e1fe10ab5b527b078e/metanl/extprocess.py#L144-L157 |
commonsense/metanl | metanl/extprocess.py | ProcessWrapper.normalize_list | def normalize_list(self, text, cache=None):
"""
Get a canonical list representation of text, with words
separated and reduced to their base forms.
TODO: use the cache.
"""
words = []
analysis = self.analyze(text)
for record in analysis:
if not... | python | def normalize_list(self, text, cache=None):
"""
Get a canonical list representation of text, with words
separated and reduced to their base forms.
TODO: use the cache.
"""
words = []
analysis = self.analyze(text)
for record in analysis:
if not... | [
"def",
"normalize_list",
"(",
"self",
",",
"text",
",",
"cache",
"=",
"None",
")",
":",
"words",
"=",
"[",
"]",
"analysis",
"=",
"self",
".",
"analyze",
"(",
"text",
")",
"for",
"record",
"in",
"analysis",
":",
"if",
"not",
"self",
".",
"is_stopword_... | Get a canonical list representation of text, with words
separated and reduced to their base forms.
TODO: use the cache. | [
"Get",
"a",
"canonical",
"list",
"representation",
"of",
"text",
"with",
"words",
"separated",
"and",
"reduced",
"to",
"their",
"base",
"forms",
"."
] | train | https://github.com/commonsense/metanl/blob/4b9ae8353489cc409bebd7e1fe10ab5b527b078e/metanl/extprocess.py#L171-L186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.