hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d5a779f6634698d349f1b247ecd43db921fa8a87 | kenjyco/aws-info-helper | aws_info_helper/__init__.py | [
"MIT"
] | Python | find_local_pem | <not_specific> | def find_local_pem(pem):
"""Given the name of pem file, find its absolute path in ~/.ssh"""
pem = pem if pem.endswith('.pem') else pem + '.pem'
dirname = os.path.abspath(os.path.expanduser('~/.ssh'))
for dirpath, dirnames, filenames in walk(dirname, topdown=True):
if pem in filenames:
... | Given the name of pem file, find its absolute path in ~/.ssh | Given the name of pem file, find its absolute path in ~/.ssh | [
"Given",
"the",
"name",
"of",
"pem",
"file",
"find",
"its",
"absolute",
"path",
"in",
"~",
"/",
".",
"ssh"
] | def find_local_pem(pem):
pem = pem if pem.endswith('.pem') else pem + '.pem'
dirname = os.path.abspath(os.path.expanduser('~/.ssh'))
for dirpath, dirnames, filenames in walk(dirname, topdown=True):
if pem in filenames:
return os.path.join(dirpath, pem) | [
"def",
"find_local_pem",
"(",
"pem",
")",
":",
"pem",
"=",
"pem",
"if",
"pem",
".",
"endswith",
"(",
"'.pem'",
")",
"else",
"pem",
"+",
"'.pem'",
"dirname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~... | Given the name of pem file, find its absolute path in ~/.ssh | [
"Given",
"the",
"name",
"of",
"pem",
"file",
"find",
"its",
"absolute",
"path",
"in",
"~",
"/",
".",
"ssh"
] | [
"\"\"\"Given the name of pem file, find its absolute path in ~/.ssh\"\"\""
] | [
{
"param": "pem",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pem",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d5a779f6634698d349f1b247ecd43db921fa8a87 | kenjyco/aws-info-helper | aws_info_helper/__init__.py | [
"MIT"
] | Python | do_ssh | <not_specific> | def do_ssh(ip, pem_file, user, command='', timeout=None, verbose=False):
"""Actually SSH to a server
- ip: IP address
- pem_file: absolute path to pem file
- user: remote SSH user
- command: an optional command to run on the remote server
- if a command is specified, it will be run on the r... | Actually SSH to a server
- ip: IP address
- pem_file: absolute path to pem file
- user: remote SSH user
- command: an optional command to run on the remote server
- if a command is specified, it will be run on the remote server and
the output will be returned
- if no command i... | Actually SSH to a server
ip: IP address
pem_file: absolute path to pem file
user: remote SSH user
command: an optional command to run on the remote server
if a command is specified, it will be run on the remote server and
the output will be returned
if no command is specified, the SSH session will be interactive | [
"Actually",
"SSH",
"to",
"a",
"server",
"ip",
":",
"IP",
"address",
"pem_file",
":",
"absolute",
"path",
"to",
"pem",
"file",
"user",
":",
"remote",
"SSH",
"user",
"command",
":",
"an",
"optional",
"command",
"to",
"run",
"on",
"the",
"remote",
"server",... | def do_ssh(ip, pem_file, user, command='', timeout=None, verbose=False):
ssh_command = 'ssh -i {} -o "StrictHostKeyChecking no" -o ConnectTimeout=2 {}@{}'
cmd = ssh_command.format(pem_file, user, ip)
if command:
cmd = cmd + ' -t {}'.format(repr(command))
if verbose:
print(cmd)
result... | [
"def",
"do_ssh",
"(",
"ip",
",",
"pem_file",
",",
"user",
",",
"command",
"=",
"''",
",",
"timeout",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"ssh_command",
"=",
"'ssh -i {} -o \"StrictHostKeyChecking no\" -o ConnectTimeout=2 {}@{}'",
"cmd",
"=",
"ss... | Actually SSH to a server
ip: IP address
pem_file: absolute path to pem file
user: remote SSH user
command: an optional command to run on the remote server
if a command is specified, it will be run on the remote server and
the output will be returned
if no command is specified, the SSH session will be interactive | [
"Actually",
"SSH",
"to",
"a",
"server",
"ip",
":",
"IP",
"address",
"pem_file",
":",
"absolute",
"path",
"to",
"pem",
"file",
"user",
":",
"remote",
"SSH",
"user",
"command",
":",
"an",
"optional",
"command",
"to",
"run",
"on",
"the",
"remote",
"server",... | [
"\"\"\"Actually SSH to a server\n\n - ip: IP address\n - pem_file: absolute path to pem file\n - user: remote SSH user\n - command: an optional command to run on the remote server\n - if a command is specified, it will be run on the remote server and\n the output will be returned\n ... | [
{
"param": "ip",
"type": null
},
{
"param": "pem_file",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "command",
"type": null
},
{
"param": "timeout",
"type": null
},
{
"param": "verbose",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ip",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pem_file",
"type": null,
"docstring": null,
"docstring_tokens":... |
afdd4d5238da0e61e3444c319f7e21ece0927976 | smorehouse/bump2version | tests/test_version_part.py | [
"MIT"
] | Python | confvpc | <not_specific> | def confvpc(request):
"""Return a three-part and a two-part version part configuration."""
if request.param is None:
return NumericVersionPartConfiguration()
else:
return ConfiguredVersionPartConfiguration(*request.param) | Return a three-part and a two-part version part configuration. | Return a three-part and a two-part version part configuration. | [
"Return",
"a",
"three",
"-",
"part",
"and",
"a",
"two",
"-",
"part",
"version",
"part",
"configuration",
"."
] | def confvpc(request):
if request.param is None:
return NumericVersionPartConfiguration()
else:
return ConfiguredVersionPartConfiguration(*request.param) | [
"def",
"confvpc",
"(",
"request",
")",
":",
"if",
"request",
".",
"param",
"is",
"None",
":",
"return",
"NumericVersionPartConfiguration",
"(",
")",
"else",
":",
"return",
"ConfiguredVersionPartConfiguration",
"(",
"*",
"request",
".",
"param",
")"
] | Return a three-part and a two-part version part configuration. | [
"Return",
"a",
"three",
"-",
"part",
"and",
"a",
"two",
"-",
"part",
"version",
"part",
"configuration",
"."
] | [
"\"\"\"Return a three-part and a two-part version part configuration.\"\"\""
] | [
{
"param": "request",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "request",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
91f362431dcb873e8827791c06b95fd55bd1a2b7 | DominusSnake/pyCraft | minecraft/networking/connection.py | [
"Apache-2.0"
] | Python | write_packet | null | def write_packet(self, packet, force=False):
"""Writes a packet to the server.
If force is set to true, the method attempts to acquire the write lock
and write the packet out immediately, and as such may block.
If force is false then the packet will be added to the end of the
p... | Writes a packet to the server.
If force is set to true, the method attempts to acquire the write lock
and write the packet out immediately, and as such may block.
If force is false then the packet will be added to the end of the
packet writing queue to be sent 'as soon as possible'
... | Writes a packet to the server.
If force is set to true, the method attempts to acquire the write lock
and write the packet out immediately, and as such may block.
If force is false then the packet will be added to the end of the
packet writing queue to be sent 'as soon as possible' | [
"Writes",
"a",
"packet",
"to",
"the",
"server",
".",
"If",
"force",
"is",
"set",
"to",
"true",
"the",
"method",
"attempts",
"to",
"acquire",
"the",
"write",
"lock",
"and",
"write",
"the",
"packet",
"out",
"immediately",
"and",
"as",
"such",
"may",
"block... | def write_packet(self, packet, force=False):
if force:
self._write_lock.acquire()
if self.options.compression_enabled:
packet.write(self.socket, self.options.compression_threshold)
else:
packet.write(self.socket)
self._write_lock.re... | [
"def",
"write_packet",
"(",
"self",
",",
"packet",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
":",
"self",
".",
"_write_lock",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"options",
".",
"compression_enabled",
":",
"packet",
".",
"write",
"(... | Writes a packet to the server. | [
"Writes",
"a",
"packet",
"to",
"the",
"server",
"."
] | [
"\"\"\"Writes a packet to the server.\n\n If force is set to true, the method attempts to acquire the write lock\n and write the packet out immediately, and as such may block.\n\n If force is false then the packet will be added to the end of the\n packet writing queue to be sent 'as soon... | [
{
"param": "self",
"type": null
},
{
"param": "packet",
"type": null
},
{
"param": "force",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "packet",
"type": null,
"docstring": "The :class:`network.packets.Pa... |
91f362431dcb873e8827791c06b95fd55bd1a2b7 | DominusSnake/pyCraft | minecraft/networking/connection.py | [
"Apache-2.0"
] | Python | register_packet_listener | null | def register_packet_listener(self, method, *args):
"""
Registers a listener method which will be notified when a packet of
a selected type is received
:param method: The method which will be called back with the packet
: args: The packets to listen for
"""
self.p... |
Registers a listener method which will be notified when a packet of
a selected type is received
:param method: The method which will be called back with the packet
: args: The packets to listen for
| Registers a listener method which will be notified when a packet of
a selected type is received | [
"Registers",
"a",
"listener",
"method",
"which",
"will",
"be",
"notified",
"when",
"a",
"packet",
"of",
"a",
"selected",
"type",
"is",
"received"
] | def register_packet_listener(self, method, *args):
self.packet_listeners.append(packets.PacketListener(method, *args)) | [
"def",
"register_packet_listener",
"(",
"self",
",",
"method",
",",
"*",
"args",
")",
":",
"self",
".",
"packet_listeners",
".",
"append",
"(",
"packets",
".",
"PacketListener",
"(",
"method",
",",
"*",
"args",
")",
")"
] | Registers a listener method which will be notified when a packet of
a selected type is received | [
"Registers",
"a",
"listener",
"method",
"which",
"will",
"be",
"notified",
"when",
"a",
"packet",
"of",
"a",
"selected",
"type",
"is",
"received"
] | [
"\"\"\"\n Registers a listener method which will be notified when a packet of\n a selected type is received\n\n :param method: The method which will be called back with the packet\n : args: The packets to listen for\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "method",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "method",
"type": null,
"docstring": "The method which will be calle... |
91f362431dcb873e8827791c06b95fd55bd1a2b7 | DominusSnake/pyCraft | minecraft/networking/connection.py | [
"Apache-2.0"
] | Python | connect | null | def connect(self):
"""Attempt to begin connecting to the server
"""
self._connect()
self._handshake()
self.reactor = LoginReactor(self)
self._start_network_thread()
login_start_packet = packets.LoginStartPacket()
login_start_packet.name = self.auth_token.... | Attempt to begin connecting to the server
| Attempt to begin connecting to the server | [
"Attempt",
"to",
"begin",
"connecting",
"to",
"the",
"server"
] | def connect(self):
self._connect()
self._handshake()
self.reactor = LoginReactor(self)
self._start_network_thread()
login_start_packet = packets.LoginStartPacket()
login_start_packet.name = self.auth_token.profile.name
self.write_packet(login_start_packet)
... | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_handshake",
"(",
")",
"self",
".",
"reactor",
"=",
"LoginReactor",
"(",
"self",
")",
"self",
".",
"_start_network_thread",
"(",
")",
"login_start_packet",
"=",
"pa... | Attempt to begin connecting to the server | [
"Attempt",
"to",
"begin",
"connecting",
"to",
"the",
"server"
] | [
"\"\"\"Attempt to begin connecting to the server\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0ff22c898e45764a4ca2eaaf04423b484d2ce759 | DominusSnake/pyCraft | minecraft/networking/packets.py | [
"Apache-2.0"
] | Python | send | null | def send(self, value):
"""
Writes the given bytes to the buffer, designed to emulate socket.send
:param value: The bytes to write
"""
self.bytes.write(value) |
Writes the given bytes to the buffer, designed to emulate socket.send
:param value: The bytes to write
| Writes the given bytes to the buffer, designed to emulate socket.send | [
"Writes",
"the",
"given",
"bytes",
"to",
"the",
"buffer",
"designed",
"to",
"emulate",
"socket",
".",
"send"
] | def send(self, value):
self.bytes.write(value) | [
"def",
"send",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bytes",
".",
"write",
"(",
"value",
")"
] | Writes the given bytes to the buffer, designed to emulate socket.send | [
"Writes",
"the",
"given",
"bytes",
"to",
"the",
"buffer",
"designed",
"to",
"emulate",
"socket",
".",
"send"
] | [
"\"\"\"\n Writes the given bytes to the buffer, designed to emulate socket.send\n :param value: The bytes to write\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "value",
"type": null,
"docstring": "The bytes to write",
"doc... |
34564b159eadee89a4edfd66b1368d33c64c5ab2 | reinvantveer/topography-detection | model/mrcnn/cemeteries_dataset.py | [
"MIT"
] | Python | load_mask | <not_specific> | def load_mask(self, image_id):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
image_info = self.image_info[... | Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
| Generate instance masks for an image. | [
"Generate",
"instance",
"masks",
"for",
"an",
"image",
"."
] | def load_mask(self, image_id):
image_info = self.image_info[image_id]
if image_info["source"] != "cemeteries":
return super(self.__class__, self).load_mask(image_id)
info = self.image_info[image_id]
mask_shape = wkt.loads(info['mask_shape'])
if mask_shape.geom_type ==... | [
"def",
"load_mask",
"(",
"self",
",",
"image_id",
")",
":",
"image_info",
"=",
"self",
".",
"image_info",
"[",
"image_id",
"]",
"if",
"image_info",
"[",
"\"source\"",
"]",
"!=",
"\"cemeteries\"",
":",
"return",
"super",
"(",
"self",
".",
"__class__",
",",
... | Generate instance masks for an image. | [
"Generate",
"instance",
"masks",
"for",
"an",
"image",
"."
] | [
"\"\"\"Generate instance masks for an image.\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n \"\"\"",
"# Convert polygons to a bitmap mask of shape",
"# [he... | [
{
"param": "self",
"type": null
},
{
"param": "image_id",
"type": null
}
] | {
"returns": [
{
"docstring": "A bool array of shape [height, width, instance count] with\none mask per instance.\nclass_ids: a 1D array of class IDs of the instance masks.",
"docstring_tokens": [
"A",
"bool",
"array",
"of",
"shape",
"[",
"height... |
34564b159eadee89a4edfd66b1368d33c64c5ab2 | reinvantveer/topography-detection | model/mrcnn/cemeteries_dataset.py | [
"MIT"
] | Python | image_reference | <not_specific> | def image_reference(self, image_id):
"""Return the path of the image."""
info = self.image_info[image_id]
if info["source"] == "cemeteries":
return info["path"]
else:
super(self.__class__, self).image_reference(image_id) | Return the path of the image. | Return the path of the image. | [
"Return",
"the",
"path",
"of",
"the",
"image",
"."
] | def image_reference(self, image_id):
info = self.image_info[image_id]
if info["source"] == "cemeteries":
return info["path"]
else:
super(self.__class__, self).image_reference(image_id) | [
"def",
"image_reference",
"(",
"self",
",",
"image_id",
")",
":",
"info",
"=",
"self",
".",
"image_info",
"[",
"image_id",
"]",
"if",
"info",
"[",
"\"source\"",
"]",
"==",
"\"cemeteries\"",
":",
"return",
"info",
"[",
"\"path\"",
"]",
"else",
":",
"super... | Return the path of the image. | [
"Return",
"the",
"path",
"of",
"the",
"image",
"."
] | [
"\"\"\"Return the path of the image.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "image_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "image_id",
"type": null,
"docstring": null,
"docstring_tokens... |
0921681d3110f7aed9b8ae15943b92c83adcf383 | reinvantveer/topography-detection | model/train.py | [
"MIT"
] | Python | reset | <not_specific> | def reset(hp):
"""
Initialize the hidden state of the core network
and the location vector.
This is called once every time a new minibatch
`x` is introduced.
"""
dtype = torch.cuda.FloatTensor
h_t = torch.zeros(hp['BATCH_SIZE'], hp['HIDDEN_SIZE'])
h_t = Variable(h_t).type(dtype)
... |
Initialize the hidden state of the core network
and the location vector.
This is called once every time a new minibatch
`x` is introduced.
| Initialize the hidden state of the core network
and the location vector.
This is called once every time a new minibatch
`x` is introduced. | [
"Initialize",
"the",
"hidden",
"state",
"of",
"the",
"core",
"network",
"and",
"the",
"location",
"vector",
".",
"This",
"is",
"called",
"once",
"every",
"time",
"a",
"new",
"minibatch",
"`",
"x",
"`",
"is",
"introduced",
"."
] | def reset(hp):
dtype = torch.cuda.FloatTensor
h_t = torch.zeros(hp['BATCH_SIZE'], hp['HIDDEN_SIZE'])
h_t = Variable(h_t).type(dtype)
l_t = torch.Tensor(hp['BATCH_SIZE'], 2).uniform_(-1, 1)
l_t = Variable(l_t).type(dtype)
return h_t, l_t | [
"def",
"reset",
"(",
"hp",
")",
":",
"dtype",
"=",
"torch",
".",
"cuda",
".",
"FloatTensor",
"h_t",
"=",
"torch",
".",
"zeros",
"(",
"hp",
"[",
"'BATCH_SIZE'",
"]",
",",
"hp",
"[",
"'HIDDEN_SIZE'",
"]",
")",
"h_t",
"=",
"Variable",
"(",
"h_t",
")",... | Initialize the hidden state of the core network
and the location vector. | [
"Initialize",
"the",
"hidden",
"state",
"of",
"the",
"core",
"network",
"and",
"the",
"location",
"vector",
"."
] | [
"\"\"\"\n Initialize the hidden state of the core network\n and the location vector.\n\n This is called once every time a new minibatch\n `x` is introduced.\n \"\"\""
] | [
{
"param": "hp",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "hp",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0921681d3110f7aed9b8ae15943b92c83adcf383 | reinvantveer/topography-detection | model/train.py | [
"MIT"
] | Python | train_one_epoch | <not_specific> | def train_one_epoch(model, optimizer, train_loader, epoch, hp):
"""
Train the model for 1 epoch of the training set.
An epoch corresponds to one full pass through the entire
training set in successive mini-batches.
"""
batch_time = AverageMeter()
losses = AverageMeter()
accs = AverageMet... |
Train the model for 1 epoch of the training set.
An epoch corresponds to one full pass through the entire
training set in successive mini-batches.
| Train the model for 1 epoch of the training set.
An epoch corresponds to one full pass through the entire
training set in successive mini-batches. | [
"Train",
"the",
"model",
"for",
"1",
"epoch",
"of",
"the",
"training",
"set",
".",
"An",
"epoch",
"corresponds",
"to",
"one",
"full",
"pass",
"through",
"the",
"entire",
"training",
"set",
"in",
"successive",
"mini",
"-",
"batches",
"."
] | def train_one_epoch(model, optimizer, train_loader, epoch, hp):
batch_time = AverageMeter()
losses = AverageMeter()
accs = AverageMeter()
tic = time.time()
with tqdm(total=hp['NUM_TRAIN']) as pbar:
for sample_index, (x, y) in enumerate(train_loader):
x, y = x.cuda(), y.cuda()
... | [
"def",
"train_one_epoch",
"(",
"model",
",",
"optimizer",
",",
"train_loader",
",",
"epoch",
",",
"hp",
")",
":",
"batch_time",
"=",
"AverageMeter",
"(",
")",
"losses",
"=",
"AverageMeter",
"(",
")",
"accs",
"=",
"AverageMeter",
"(",
")",
"tic",
"=",
"ti... | Train the model for 1 epoch of the training set. | [
"Train",
"the",
"model",
"for",
"1",
"epoch",
"of",
"the",
"training",
"set",
"."
] | [
"\"\"\"\n Train the model for 1 epoch of the training set.\n An epoch corresponds to one full pass through the entire\n training set in successive mini-batches.\n \"\"\"",
"# initialize location vector and hidden state",
"# We need to set this to train on variable batch size",
"# save images",
"... | [
{
"param": "model",
"type": null
},
{
"param": "optimizer",
"type": null
},
{
"param": "train_loader",
"type": null
},
{
"param": "epoch",
"type": null
},
{
"param": "hp",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "optimizer",
"type": null,
"docstring": null,
"docstring_toke... |
0921681d3110f7aed9b8ae15943b92c83adcf383 | reinvantveer/topography-detection | model/train.py | [
"MIT"
] | Python | validate | <not_specific> | def validate(model, valid_loader, epoch, hp):
"""
Evaluate the model on the validation set.
"""
losses = AverageMeter()
accs = AverageMeter()
for i, (x, y) in enumerate(valid_loader):
x, y = x.cuda(), y.cuda()
x, y = Variable(x), Variable(y)
# duplicate 10 times
... |
Evaluate the model on the validation set.
| Evaluate the model on the validation set. | [
"Evaluate",
"the",
"model",
"on",
"the",
"validation",
"set",
"."
] | def validate(model, valid_loader, epoch, hp):
losses = AverageMeter()
accs = AverageMeter()
for i, (x, y) in enumerate(valid_loader):
x, y = x.cuda(), y.cuda()
x, y = Variable(x), Variable(y)
x = x.repeat(hp['M'], 1, 1, 1)
hp['VALIDATE_BATCH_SIZE'] = x.shape[0]
h_t, l... | [
"def",
"validate",
"(",
"model",
",",
"valid_loader",
",",
"epoch",
",",
"hp",
")",
":",
"losses",
"=",
"AverageMeter",
"(",
")",
"accs",
"=",
"AverageMeter",
"(",
")",
"for",
"i",
",",
"(",
"x",
",",
"y",
")",
"in",
"enumerate",
"(",
"valid_loader",... | Evaluate the model on the validation set. | [
"Evaluate",
"the",
"model",
"on",
"the",
"validation",
"set",
"."
] | [
"\"\"\"\n Evaluate the model on the validation set.\n \"\"\"",
"# duplicate 10 times",
"# initialize location vector and hidden state",
"# extract the glimpses",
"# forward pass through model",
"# store",
"# last iteration",
"# convert list to tensors and reshape",
"# average",
"# calculate ... | [
{
"param": "model",
"type": null
},
{
"param": "valid_loader",
"type": null
},
{
"param": "epoch",
"type": null
},
{
"param": "hp",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "valid_loader",
"type": null,
"docstring": null,
"docstring_t... |
abc61ff96fcac3a735865ef9af4de7fae66e9a6b | reinvantveer/topography-detection | model/mrcnn/wind_turbines_dataset.py | [
"MIT"
] | Python | load_mask | <not_specific> | def load_mask(self, image_id):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# If not a balloon dataset im... | Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
| Generate instance masks for an image. | [
"Generate",
"instance",
"masks",
"for",
"an",
"image",
"."
] | def load_mask(self, image_id):
image_info = self.image_info[image_id]
if image_info["source"] != "windturbines":
return super(self.__class__, self).load_mask(image_id)
info = self.image_info[image_id]
mask = np.zeros([info["height"], info["width"], len(info["centroids"])],
... | [
"def",
"load_mask",
"(",
"self",
",",
"image_id",
")",
":",
"image_info",
"=",
"self",
".",
"image_info",
"[",
"image_id",
"]",
"if",
"image_info",
"[",
"\"source\"",
"]",
"!=",
"\"windturbines\"",
":",
"return",
"super",
"(",
"self",
".",
"__class__",
","... | Generate instance masks for an image. | [
"Generate",
"instance",
"masks",
"for",
"an",
"image",
"."
] | [
"\"\"\"Generate instance masks for an image.\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n \"\"\"",
"# If not a balloon dataset image, delegate to parent cl... | [
{
"param": "self",
"type": null
},
{
"param": "image_id",
"type": null
}
] | {
"returns": [
{
"docstring": "A bool array of shape [height, width, instance count] with\none mask per instance.\nclass_ids: a 1D array of class IDs of the instance masks.",
"docstring_tokens": [
"A",
"bool",
"array",
"of",
"shape",
"[",
"height... |
abc61ff96fcac3a735865ef9af4de7fae66e9a6b | reinvantveer/topography-detection | model/mrcnn/wind_turbines_dataset.py | [
"MIT"
] | Python | image_reference | <not_specific> | def image_reference(self, image_id):
"""Return the path of the image."""
info = self.image_info[image_id]
if info["source"] == "windturbines":
return info["path"]
else:
super(self.__class__, self).image_reference(image_id) | Return the path of the image. | Return the path of the image. | [
"Return",
"the",
"path",
"of",
"the",
"image",
"."
] | def image_reference(self, image_id):
info = self.image_info[image_id]
if info["source"] == "windturbines":
return info["path"]
else:
super(self.__class__, self).image_reference(image_id) | [
"def",
"image_reference",
"(",
"self",
",",
"image_id",
")",
":",
"info",
"=",
"self",
".",
"image_info",
"[",
"image_id",
"]",
"if",
"info",
"[",
"\"source\"",
"]",
"==",
"\"windturbines\"",
":",
"return",
"info",
"[",
"\"path\"",
"]",
"else",
":",
"sup... | Return the path of the image. | [
"Return",
"the",
"path",
"of",
"the",
"image",
"."
] | [
"\"\"\"Return the path of the image.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "image_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "image_id",
"type": null,
"docstring": null,
"docstring_tokens... |
d780a9c71124ddfb6363c4e900986f7bff43a3a3 | Pots8/project2 | app.py | [
"MIT"
] | Python | staterisks | <not_specific> | def staterisks():
"""Return a list of sample names."""
# Use Pandas to perform the sql query
stmt = db.session.query(risk_data).statement
df = pd.read_sql_query(stmt, db.session.bind)
# Return a list of the column names (sample names)
return jsonify(list(df.columns)[:]) | Return a list of sample names. | Return a list of sample names. | [
"Return",
"a",
"list",
"of",
"sample",
"names",
"."
] | def staterisks():
stmt = db.session.query(risk_data).statement
df = pd.read_sql_query(stmt, db.session.bind)
return jsonify(list(df.columns)[:]) | [
"def",
"staterisks",
"(",
")",
":",
"stmt",
"=",
"db",
".",
"session",
".",
"query",
"(",
"risk_data",
")",
".",
"statement",
"df",
"=",
"pd",
".",
"read_sql_query",
"(",
"stmt",
",",
"db",
".",
"session",
".",
"bind",
")",
"return",
"jsonify",
"(",
... | Return a list of sample names. | [
"Return",
"a",
"list",
"of",
"sample",
"names",
"."
] | [
"\"\"\"Return a list of sample names.\"\"\"",
"# Use Pandas to perform the sql query",
"# Return a list of the column names (sample names)"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
d980d59a5dae22abeccb30b99c0902cbc9391c23 | emlove/pyzerproc | pyzerproc/light.py | [
"Apache-2.0"
] | Python | is_connected | <not_specific> | async def is_connected(self, *args, timeout=None):
"""Returns true if the light is connected."""
try:
return await asyncio.wait_for(
self._client.is_connected(),
self._default_timeout if timeout is None else timeout)
except asyncio.TimeoutError:
... | Returns true if the light is connected. | Returns true if the light is connected. | [
"Returns",
"true",
"if",
"the",
"light",
"is",
"connected",
"."
] | async def is_connected(self, *args, timeout=None):
try:
return await asyncio.wait_for(
self._client.is_connected(),
self._default_timeout if timeout is None else timeout)
except asyncio.TimeoutError:
return False
except Exception as ex:
... | [
"async",
"def",
"is_connected",
"(",
"self",
",",
"*",
"args",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"return",
"await",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"_client",
".",
"is_connected",
"(",
")",
",",
"self",
".",
"_default_tim... | Returns true if the light is connected. | [
"Returns",
"true",
"if",
"the",
"light",
"is",
"connected",
"."
] | [
"\"\"\"Returns true if the light is connected.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "timeout",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "timeout",
"type": null,
"docstring": null,
"docstring_tokens"... |
d980d59a5dae22abeccb30b99c0902cbc9391c23 | emlove/pyzerproc | pyzerproc/light.py | [
"Apache-2.0"
] | Python | disconnect | null | async def disconnect(self, *args, timeout=None):
"""Close the connection to the light."""
_LOGGER.debug("Disconnecting from %s", self._address)
try:
await asyncio.wait_for(
self._do_disconnect(),
self._default_timeout if timeout is None else timeout)
... | Close the connection to the light. | Close the connection to the light. | [
"Close",
"the",
"connection",
"to",
"the",
"light",
"."
] | async def disconnect(self, *args, timeout=None):
_LOGGER.debug("Disconnecting from %s", self._address)
try:
await asyncio.wait_for(
self._do_disconnect(),
self._default_timeout if timeout is None else timeout)
except Exception as ex:
raise ... | [
"async",
"def",
"disconnect",
"(",
"self",
",",
"*",
"args",
",",
"timeout",
"=",
"None",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Disconnecting from %s\"",
",",
"self",
".",
"_address",
")",
"try",
":",
"await",
"asyncio",
".",
"wait_for",
"(",
"self"... | Close the connection to the light. | [
"Close",
"the",
"connection",
"to",
"the",
"light",
"."
] | [
"\"\"\"Close the connection to the light.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "timeout",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "timeout",
"type": null,
"docstring": null,
"docstring_tokens"... |
d980d59a5dae22abeccb30b99c0902cbc9391c23 | emlove/pyzerproc | pyzerproc/light.py | [
"Apache-2.0"
] | Python | _handle_data | null | def _handle_data(self, handle, value):
"""Handle an incoming notification message."""
_LOGGER.debug("Got handle '%s' and value %s", handle, hexlify(value))
try:
self._notification_queue.put_nowait(value)
except asyncio.QueueFull:
_LOGGER.debug("Discarding duplicat... | Handle an incoming notification message. | Handle an incoming notification message. | [
"Handle",
"an",
"incoming",
"notification",
"message",
"."
] | def _handle_data(self, handle, value):
_LOGGER.debug("Got handle '%s' and value %s", handle, hexlify(value))
try:
self._notification_queue.put_nowait(value)
except asyncio.QueueFull:
_LOGGER.debug("Discarding duplicate response", exc_info=True) | [
"def",
"_handle_data",
"(",
"self",
",",
"handle",
",",
"value",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Got handle '%s' and value %s\"",
",",
"handle",
",",
"hexlify",
"(",
"value",
")",
")",
"try",
":",
"self",
".",
"_notification_queue",
".",
"put_nowa... | Handle an incoming notification message. | [
"Handle",
"an",
"incoming",
"notification",
"message",
"."
] | [
"\"\"\"Handle an incoming notification message.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "handle",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "handle",
"type": null,
"docstring": null,
"docstring_tokens":... |
d980d59a5dae22abeccb30b99c0902cbc9391c23 | emlove/pyzerproc | pyzerproc/light.py | [
"Apache-2.0"
] | Python | _do_get_state | <not_specific> | async def _do_get_state(self):
"""Get the current state of the light"""
# Clear the queue if a value is somehow left over
try:
self._notification_queue.get_nowait()
except asyncio.QueueEmpty:
pass
await self._write(CHARACTERISTIC_COMMAND_WRITE, b'\xEF\x01... | Get the current state of the light | Get the current state of the light | [
"Get",
"the",
"current",
"state",
"of",
"the",
"light"
] | async def _do_get_state(self):
try:
self._notification_queue.get_nowait()
except asyncio.QueueEmpty:
pass
await self._write(CHARACTERISTIC_COMMAND_WRITE, b'\xEF\x01\x77')
response = await self._notification_queue.get()
on_off_value = int(response[2])
... | [
"async",
"def",
"_do_get_state",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_notification_queue",
".",
"get_nowait",
"(",
")",
"except",
"asyncio",
".",
"QueueEmpty",
":",
"pass",
"await",
"self",
".",
"_write",
"(",
"CHARACTERISTIC_COMMAND_WRITE",
",",
... | Get the current state of the light | [
"Get",
"the",
"current",
"state",
"of",
"the",
"light"
] | [
"\"\"\"Get the current state of the light\"\"\"",
"# Clear the queue if a value is somehow left over",
"# Normalize and clamp from 0-31, to 0-255"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d980d59a5dae22abeccb30b99c0902cbc9391c23 | emlove/pyzerproc | pyzerproc/light.py | [
"Apache-2.0"
] | Python | _write | null | async def _write(self, uuid, value):
"""Internal method to write to the device"""
_LOGGER.debug("Writing 0x%s to characteristic %s", value.hex(), uuid)
try:
await self._client.write_gatt_char(uuid, bytearray(value))
except Exception as ex:
raise ZerprocException()... | Internal method to write to the device | Internal method to write to the device | [
"Internal",
"method",
"to",
"write",
"to",
"the",
"device"
] | async def _write(self, uuid, value):
_LOGGER.debug("Writing 0x%s to characteristic %s", value.hex(), uuid)
try:
await self._client.write_gatt_char(uuid, bytearray(value))
except Exception as ex:
raise ZerprocException() from ex
_LOGGER.debug("Wrote 0x%s to charact... | [
"async",
"def",
"_write",
"(",
"self",
",",
"uuid",
",",
"value",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Writing 0x%s to characteristic %s\"",
",",
"value",
".",
"hex",
"(",
")",
",",
"uuid",
")",
"try",
":",
"await",
"self",
".",
"_client",
".",
"... | Internal method to write to the device | [
"Internal",
"method",
"to",
"write",
"to",
"the",
"device"
] | [
"\"\"\"Internal method to write to the device\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "uuid",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "uuid",
"type": null,
"docstring": null,
"docstring_tokens": [... |
aad71fdff8c3505f4d8113bbc27af2632afc97e0 | emlove/pyzerproc | tests/test_light.py | [
"Apache-2.0"
] | Python | send_response | null | async def send_response(*args, **kwargs):
"""Simulate a response from the light"""
light._handle_data(
63, b'\x66\xe3\x23\x16\x24\x01\x10\x05\x1C\x00\x01\x99')
light._handle_data(
63, b'\x66\xe3\x23\x16\x24\x01\x10\x05\x1C\x00\x01\x99') | Simulate a response from the light | Simulate a response from the light | [
"Simulate",
"a",
"response",
"from",
"the",
"light"
] | async def send_response(*args, **kwargs):
light._handle_data(
63, b'\x66\xe3\x23\x16\x24\x01\x10\x05\x1C\x00\x01\x99')
light._handle_data(
63, b'\x66\xe3\x23\x16\x24\x01\x10\x05\x1C\x00\x01\x99') | [
"async",
"def",
"send_response",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"light",
".",
"_handle_data",
"(",
"63",
",",
"b'\\x66\\xe3\\x23\\x16\\x24\\x01\\x10\\x05\\x1C\\x00\\x01\\x99'",
")",
"light",
".",
"_handle_data",
"(",
"63",
",",
"b'\\x66\\xe3\\x23\\... | Simulate a response from the light | [
"Simulate",
"a",
"response",
"from",
"the",
"light"
] | [
"\"\"\"Simulate a response from the light\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
567377005d9ef305fd778c2d671f333ec19b8118 | Lakshay-sethi/dataprep | dataprep/eda/distribution/compute/__init__.py | [
"MIT"
] | Python | compute | Intermediate | def compute(
df: Union[pd.DataFrame, dd.DataFrame],
x: Optional[str] = None,
y: Optional[str] = None,
z: Optional[str] = None,
*,
cfg: Union[Config, Dict[str, Any], None] = None,
display: Optional[List[str]] = None,
dtype: Optional[DTypeDef] = None,
) -> Intermediate:
"""
All in ... |
All in one compute function.
Parameters
----------
df
DataFrame from which visualizations are generated
cfg: Union[Config, Dict[str, Any], None], default None
When a user call plot(), the created Config object will be passed to compute().
When a user call compute() directly... | All in one compute function.
Parameters
df
DataFrame from which visualizations are generated
cfg: Union[Config, Dict[str, Any], None], default None
When a user call plot(), the created Config object will be passed to compute().
When a user call compute() directly, if he/she wants to customize the output,
cfg is a dict... | [
"All",
"in",
"one",
"compute",
"function",
".",
"Parameters",
"df",
"DataFrame",
"from",
"which",
"visualizations",
"are",
"generated",
"cfg",
":",
"Union",
"[",
"Config",
"Dict",
"[",
"str",
"Any",
"]",
"None",
"]",
"default",
"None",
"When",
"a",
"user",... | def compute(
df: Union[pd.DataFrame, dd.DataFrame],
x: Optional[str] = None,
y: Optional[str] = None,
z: Optional[str] = None,
*,
cfg: Union[Config, Dict[str, Any], None] = None,
display: Optional[List[str]] = None,
dtype: Optional[DTypeDef] = None,
) -> Intermediate:
suppress_warnin... | [
"def",
"compute",
"(",
"df",
":",
"Union",
"[",
"pd",
".",
"DataFrame",
",",
"dd",
".",
"DataFrame",
"]",
",",
"x",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"y",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"z",
":",
"Optional... | All in one compute function. | [
"All",
"in",
"one",
"compute",
"function",
"."
] | [
"\"\"\"\n All in one compute function.\n\n Parameters\n ----------\n df\n DataFrame from which visualizations are generated\n cfg: Union[Config, Dict[str, Any], None], default None\n When a user call plot(), the created Config object will be passed to compute().\n When a user cal... | [
{
"param": "df",
"type": "Union[pd.DataFrame, dd.DataFrame]"
},
{
"param": "x",
"type": "Optional[str]"
},
{
"param": "y",
"type": "Optional[str]"
},
{
"param": "z",
"type": "Optional[str]"
},
{
"param": "cfg",
"type": "Union[Config, Dict[str, Any], None]"
}... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": "Union[pd.DataFrame, dd.DataFrame]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": "Optional[str]",
"docstrin... |
567377005d9ef305fd778c2d671f333ec19b8118 | Lakshay-sethi/dataprep | dataprep/eda/distribution/compute/__init__.py | [
"MIT"
] | Python | concat_latlong | Tuple[str, Any] | def concat_latlong(df: Union[pd.DataFrame, dd.DataFrame], x: Any) -> Tuple[str, Any]:
"""
Merge Latlong into one new column.
"""
name = x.lat + "_&_" + x.long
lat_long = tuple(zip(df[x.lat], df[x.long]))
return name, lat_long |
Merge Latlong into one new column.
| Merge Latlong into one new column. | [
"Merge",
"Latlong",
"into",
"one",
"new",
"column",
"."
] | def concat_latlong(df: Union[pd.DataFrame, dd.DataFrame], x: Any) -> Tuple[str, Any]:
name = x.lat + "_&_" + x.long
lat_long = tuple(zip(df[x.lat], df[x.long]))
return name, lat_long | [
"def",
"concat_latlong",
"(",
"df",
":",
"Union",
"[",
"pd",
".",
"DataFrame",
",",
"dd",
".",
"DataFrame",
"]",
",",
"x",
":",
"Any",
")",
"->",
"Tuple",
"[",
"str",
",",
"Any",
"]",
":",
"name",
"=",
"x",
".",
"lat",
"+",
"\"_&_\"",
"+",
"x",... | Merge Latlong into one new column. | [
"Merge",
"Latlong",
"into",
"one",
"new",
"column",
"."
] | [
"\"\"\"\n Merge Latlong into one new column.\n \"\"\""
] | [
{
"param": "df",
"type": "Union[pd.DataFrame, dd.DataFrame]"
},
{
"param": "x",
"type": "Any"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": "Union[pd.DataFrame, dd.DataFrame]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": "Any",
"docstring": null,
... |
ff9aa9d0127567cb06e96a75182b127983525a53 | Lakshay-sethi/dataprep | dataprep/eda/diff/compute/multiple_df.py | [
"MIT"
] | Python | compare_multiple_df | Intermediate | def compare_multiple_df(
df_list: List[dd.DataFrame], cfg: Config, dtype: Optional[DTypeDef]
) -> Intermediate:
"""
Compute function for plot_diff([df...])
Parameters
----------
dfs
Dataframe sequence to be compared.
cfg
Config instance
dtype: str or DType or dict of str... |
Compute function for plot_diff([df...])
Parameters
----------
dfs
Dataframe sequence to be compared.
cfg
Config instance
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns.
E.g. dtype = {"a"... | Compute function for plot_diff([df...])
Parameters
dfs
Dataframe sequence to be compared.
cfg
Config instance
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns. | [
"Compute",
"function",
"for",
"plot_diff",
"(",
"[",
"df",
"...",
"]",
")",
"Parameters",
"dfs",
"Dataframe",
"sequence",
"to",
"be",
"compared",
".",
"cfg",
"Config",
"instance",
"dtype",
":",
"str",
"or",
"DType",
"or",
"dict",
"of",
"str",
"or",
"dict... | def compare_multiple_df(
df_list: List[dd.DataFrame], cfg: Config, dtype: Optional[DTypeDef]
) -> Intermediate:
dfs = Dfs(df_list)
dfs_cols = dfs.columns.apply("to_list").data
labeled_cols = dict(zip(cfg.diff.label, dfs_cols))
baseline: int = cfg.diff.baseline
data: List[Any] = []
aligned_df... | [
"def",
"compare_multiple_df",
"(",
"df_list",
":",
"List",
"[",
"dd",
".",
"DataFrame",
"]",
",",
"cfg",
":",
"Config",
",",
"dtype",
":",
"Optional",
"[",
"DTypeDef",
"]",
")",
"->",
"Intermediate",
":",
"dfs",
"=",
"Dfs",
"(",
"df_list",
")",
"dfs_co... | Compute function for plot_diff([df...])
Parameters | [
"Compute",
"function",
"for",
"plot_diff",
"(",
"[",
"df",
"...",
"]",
")",
"Parameters"
] | [
"\"\"\"\n Compute function for plot_diff([df...])\n\n Parameters\n ----------\n dfs\n Dataframe sequence to be compared.\n cfg\n Config instance\n dtype: str or DType or dict of str or dict of DType, default None\n Specify Data Types for designated column or all columns.\n ... | [
{
"param": "df_list",
"type": "List[dd.DataFrame]"
},
{
"param": "cfg",
"type": "Config"
},
{
"param": "dtype",
"type": "Optional[DTypeDef]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df_list",
"type": "List[dd.DataFrame]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cfg",
"type": "Config",
"docstring": null,
... |
5dfccff4907a78f71828d512ecc9de14df415a67 | Lakshay-sethi/dataprep | dataprep/eda/missing/compute/common.py | [
"MIT"
] | Python | uni_histogram | Tuple[da.Array, ...] | def uni_histogram(
srs: dd.Series,
cfg: Config,
dtype: Optional[DTypeDef] = None,
) -> Tuple[da.Array, ...]:
"""Calculate "histogram" for both numerical and categorical."""
if is_dtype(detect_dtype(srs, dtype), Continuous()):
counts, edges = da.histogram(srs, cfg.hist.bins, (srs.min(), srs... | Calculate "histogram" for both numerical and categorical. | Calculate "histogram" for both numerical and categorical. | [
"Calculate",
"\"",
"histogram",
"\"",
"for",
"both",
"numerical",
"and",
"categorical",
"."
] | def uni_histogram(
srs: dd.Series,
cfg: Config,
dtype: Optional[DTypeDef] = None,
) -> Tuple[da.Array, ...]:
if is_dtype(detect_dtype(srs, dtype), Continuous()):
counts, edges = da.histogram(srs, cfg.hist.bins, (srs.min(), srs.max()))
centers = (edges[:-1] + edges[1:]) / 2
return... | [
"def",
"uni_histogram",
"(",
"srs",
":",
"dd",
".",
"Series",
",",
"cfg",
":",
"Config",
",",
"dtype",
":",
"Optional",
"[",
"DTypeDef",
"]",
"=",
"None",
",",
")",
"->",
"Tuple",
"[",
"da",
".",
"Array",
",",
"...",
"]",
":",
"if",
"is_dtype",
"... | Calculate "histogram" for both numerical and categorical. | [
"Calculate",
"\"",
"histogram",
"\"",
"for",
"both",
"numerical",
"and",
"categorical",
"."
] | [
"\"\"\"Calculate \"histogram\" for both numerical and categorical.\"\"\"",
"# Dask array's unique is way slower than the values_counts on Series",
"# See https://github.com/dask/dask/issues/2851",
"# centers, counts = da.unique(arr, return_counts=True)"
] | [
{
"param": "srs",
"type": "dd.Series"
},
{
"param": "cfg",
"type": "Config"
},
{
"param": "dtype",
"type": "Optional[DTypeDef]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "srs",
"type": "dd.Series",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cfg",
"type": "Config",
"docstring": null,
"docstring_t... |
5dfccff4907a78f71828d512ecc9de14df415a67 | Lakshay-sethi/dataprep | dataprep/eda/missing/compute/common.py | [
"MIT"
] | Python | histogram | Tuple[da.Array, ...] | def histogram(
arr: da.Array,
bins: Optional[int] = None,
return_edges: bool = True,
range: Optional[Tuple[int, int]] = None, # pylint: disable=redefined-builtin
dtype: Optional[DTypeDef] = None,
) -> Tuple[da.Array, ...]:
"""Calculate "histogram" for both numerical and categorical."""
if l... | Calculate "histogram" for both numerical and categorical. | Calculate "histogram" for both numerical and categorical. | [
"Calculate",
"\"",
"histogram",
"\"",
"for",
"both",
"numerical",
"and",
"categorical",
"."
] | def histogram(
arr: da.Array,
bins: Optional[int] = None,
return_edges: bool = True,
range: Optional[Tuple[int, int]] = None,
dtype: Optional[DTypeDef] = None,
) -> Tuple[da.Array, ...]:
if len(arr.shape) != 1:
raise ValueError("Histogram only supports 1-d array.")
srs = dd.from_da... | [
"def",
"histogram",
"(",
"arr",
":",
"da",
".",
"Array",
",",
"bins",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"return_edges",
":",
"bool",
"=",
"True",
",",
"range",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"="... | Calculate "histogram" for both numerical and categorical. | [
"Calculate",
"\"",
"histogram",
"\"",
"for",
"both",
"numerical",
"and",
"categorical",
"."
] | [
"# pylint: disable=redefined-builtin",
"\"\"\"Calculate \"histogram\" for both numerical and categorical.\"\"\"",
"# Dask array's unique is way slower than the values_counts on Series",
"# See https://github.com/dask/dask/issues/2851",
"# centers, counts = da.unique(arr, return_counts=True)"
] | [
{
"param": "arr",
"type": "da.Array"
},
{
"param": "bins",
"type": "Optional[int]"
},
{
"param": "return_edges",
"type": "bool"
},
{
"param": "range",
"type": "Optional[Tuple[int, int]]"
},
{
"param": "dtype",
"type": "Optional[DTypeDef]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "arr",
"type": "da.Array",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bins",
"type": "Optional[int]",
"docstring": null,
"docs... |
299d167c85e65c10913d228d0981fc1f9152470f | OCEChain/KNN | algorithms/itemSimilarity.py | [
"MIT"
] | Python | parseVector | <not_specific> | def parseVector(line):
'''
Parse each line of the specified data file, assuming a "|" delimiter.
Converts each rating to a float
'''
line = line.split("|")
return line[0],(line[1],float(line[2])) |
Parse each line of the specified data file, assuming a "|" delimiter.
Converts each rating to a float
| Parse each line of the specified data file, assuming a "|" delimiter.
Converts each rating to a float | [
"Parse",
"each",
"line",
"of",
"the",
"specified",
"data",
"file",
"assuming",
"a",
"\"",
"|",
"\"",
"delimiter",
".",
"Converts",
"each",
"rating",
"to",
"a",
"float"
] | def parseVector(line):
line = line.split("|")
return line[0],(line[1],float(line[2])) | [
"def",
"parseVector",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
"\"|\"",
")",
"return",
"line",
"[",
"0",
"]",
",",
"(",
"line",
"[",
"1",
"]",
",",
"float",
"(",
"line",
"[",
"2",
"]",
")",
")"
] | Parse each line of the specified data file, assuming a "|" delimiter. | [
"Parse",
"each",
"line",
"of",
"the",
"specified",
"data",
"file",
"assuming",
"a",
"\"",
"|",
"\"",
"delimiter",
"."
] | [
"'''\n Parse each line of the specified data file, assuming a \"|\" delimiter.\n Converts each rating to a float\n '''"
] | [
{
"param": "line",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "line",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
299d167c85e65c10913d228d0981fc1f9152470f | OCEChain/KNN | algorithms/itemSimilarity.py | [
"MIT"
] | Python | findItemPairs | <not_specific> | def findItemPairs(user_id,items_with_rating):
'''
For each user, find all item-item pairs combos. (i.e. items with the same user)
'''
for item1,item2 in combinations(items_with_rating,2):
return (item1[0],item2[0]),(item1[1],item2[1]) |
For each user, find all item-item pairs combos. (i.e. items with the same user)
| For each user, find all item-item pairs combos. | [
"For",
"each",
"user",
"find",
"all",
"item",
"-",
"item",
"pairs",
"combos",
"."
] | def findItemPairs(user_id,items_with_rating):
for item1,item2 in combinations(items_with_rating,2):
return (item1[0],item2[0]),(item1[1],item2[1]) | [
"def",
"findItemPairs",
"(",
"user_id",
",",
"items_with_rating",
")",
":",
"for",
"item1",
",",
"item2",
"in",
"combinations",
"(",
"items_with_rating",
",",
"2",
")",
":",
"return",
"(",
"item1",
"[",
"0",
"]",
",",
"item2",
"[",
"0",
"]",
")",
",",
... | For each user, find all item-item pairs combos. | [
"For",
"each",
"user",
"find",
"all",
"item",
"-",
"item",
"pairs",
"combos",
"."
] | [
"'''\n For each user, find all item-item pairs combos. (i.e. items with the same user) \n '''"
] | [
{
"param": "user_id",
"type": null
},
{
"param": "items_with_rating",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "user_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "items_with_rating",
"type": null,
"docstring": null,
"docs... |
299d167c85e65c10913d228d0981fc1f9152470f | OCEChain/KNN | algorithms/itemSimilarity.py | [
"MIT"
] | Python | calcSim | <not_specific> | def calcSim(item_pair,rating_pairs):
'''
For each item-item pair, return the specified similarity measure,
along with co_raters_count
'''
sum_xx, sum_xy, sum_yy, sum_x, sum_y, n = (0.0, 0.0, 0.0, 0.0, 0.0, 0)
for rating_pair in rating_pairs:
sum_xx += np.float(rating_pair[0]) * np.... |
For each item-item pair, return the specified similarity measure,
along with co_raters_count
| For each item-item pair, return the specified similarity measure,
along with co_raters_count | [
"For",
"each",
"item",
"-",
"item",
"pair",
"return",
"the",
"specified",
"similarity",
"measure",
"along",
"with",
"co_raters_count"
] | def calcSim(item_pair,rating_pairs):
sum_xx, sum_xy, sum_yy, sum_x, sum_y, n = (0.0, 0.0, 0.0, 0.0, 0.0, 0)
for rating_pair in rating_pairs:
sum_xx += np.float(rating_pair[0]) * np.float(rating_pair[0])
sum_yy += np.float(rating_pair[1]) * np.float(rating_pair[1])
sum_xy += np.float(rati... | [
"def",
"calcSim",
"(",
"item_pair",
",",
"rating_pairs",
")",
":",
"sum_xx",
",",
"sum_xy",
",",
"sum_yy",
",",
"sum_x",
",",
"sum_y",
",",
"n",
"=",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0",
")",
"for",
"rating_pair",
... | For each item-item pair, return the specified similarity measure,
along with co_raters_count | [
"For",
"each",
"item",
"-",
"item",
"pair",
"return",
"the",
"specified",
"similarity",
"measure",
"along",
"with",
"co_raters_count"
] | [
"''' \n For each item-item pair, return the specified similarity measure,\n along with co_raters_count\n '''",
"# sum_y += rt[1]",
"# sum_x += rt[0]"
] | [
{
"param": "item_pair",
"type": null
},
{
"param": "rating_pairs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "item_pair",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "rating_pairs",
"type": null,
"docstring": null,
"docstri... |
1a3d3f89a9dd9ee81df8718ff222bb64af9245c0 | OCEChain/KNN | algorithms/userSimilarity.py | [
"MIT"
] | Python | parseVector | <not_specific> | def parseVector(line):
'''
Parse each line of the specified data file, assuming a "|" delimiter.
Converts each rating to a float
'''
line = line.split("|")
return line[1],(line[0],float(line[2])) |
Parse each line of the specified data file, assuming a "|" delimiter.
Converts each rating to a float
| Parse each line of the specified data file, assuming a "|" delimiter.
Converts each rating to a float | [
"Parse",
"each",
"line",
"of",
"the",
"specified",
"data",
"file",
"assuming",
"a",
"\"",
"|",
"\"",
"delimiter",
".",
"Converts",
"each",
"rating",
"to",
"a",
"float"
] | def parseVector(line):
line = line.split("|")
return line[1],(line[0],float(line[2])) | [
"def",
"parseVector",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
"\"|\"",
")",
"return",
"line",
"[",
"1",
"]",
",",
"(",
"line",
"[",
"0",
"]",
",",
"float",
"(",
"line",
"[",
"2",
"]",
")",
")"
] | Parse each line of the specified data file, assuming a "|" delimiter. | [
"Parse",
"each",
"line",
"of",
"the",
"specified",
"data",
"file",
"assuming",
"a",
"\"",
"|",
"\"",
"delimiter",
"."
] | [
"'''\n Parse each line of the specified data file, assuming a \"|\" delimiter.\n Converts each rating to a float\n '''"
] | [
{
"param": "line",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "line",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
1a3d3f89a9dd9ee81df8718ff222bb64af9245c0 | OCEChain/KNN | algorithms/userSimilarity.py | [
"MIT"
] | Python | keyOnUserPair | <not_specific> | def keyOnUserPair(item_id,user_and_rating_pair):
'''
Convert each item and co_rating user pairs to a new vector
keyed on the user pair ids, with the co_ratings as their value.
'''
(user1_with_rating,user2_with_rating) = user_and_rating_pair
user1_id,user2_id = user1_with_rating[0],user2_with_r... |
Convert each item and co_rating user pairs to a new vector
keyed on the user pair ids, with the co_ratings as their value.
| Convert each item and co_rating user pairs to a new vector
keyed on the user pair ids, with the co_ratings as their value. | [
"Convert",
"each",
"item",
"and",
"co_rating",
"user",
"pairs",
"to",
"a",
"new",
"vector",
"keyed",
"on",
"the",
"user",
"pair",
"ids",
"with",
"the",
"co_ratings",
"as",
"their",
"value",
"."
] | def keyOnUserPair(item_id,user_and_rating_pair):
(user1_with_rating,user2_with_rating) = user_and_rating_pair
user1_id,user2_id = user1_with_rating[0],user2_with_rating[0]
user1_rating,user2_rating = user1_with_rating[1],user2_with_rating[1]
return (user1_id,user2_id),(user1_rating,user2_rating) | [
"def",
"keyOnUserPair",
"(",
"item_id",
",",
"user_and_rating_pair",
")",
":",
"(",
"user1_with_rating",
",",
"user2_with_rating",
")",
"=",
"user_and_rating_pair",
"user1_id",
",",
"user2_id",
"=",
"user1_with_rating",
"[",
"0",
"]",
",",
"user2_with_rating",
"[",
... | Convert each item and co_rating user pairs to a new vector
keyed on the user pair ids, with the co_ratings as their value. | [
"Convert",
"each",
"item",
"and",
"co_rating",
"user",
"pairs",
"to",
"a",
"new",
"vector",
"keyed",
"on",
"the",
"user",
"pair",
"ids",
"with",
"the",
"co_ratings",
"as",
"their",
"value",
"."
] | [
"''' \n Convert each item and co_rating user pairs to a new vector\n keyed on the user pair ids, with the co_ratings as their value. \n '''"
] | [
{
"param": "item_id",
"type": null
},
{
"param": "user_and_rating_pair",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "item_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user_and_rating_pair",
"type": null,
"docstring": null,
"d... |
1a3d3f89a9dd9ee81df8718ff222bb64af9245c0 | OCEChain/KNN | algorithms/userSimilarity.py | [
"MIT"
] | Python | calcSim | <not_specific> | def calcSim(user_pair,rating_pairs):
'''
For each user-user pair, return the specified similarity measure,
along with co_raters_count.
'''
sum_xx, sum_xy, sum_yy, sum_x, sum_y, n = (0.0, 0.0, 0.0, 0.0, 0.0, 0)
for rating_pair in rating_pairs:
sum_xx += np.float(rating_pair[0]) * np... |
For each user-user pair, return the specified similarity measure,
along with co_raters_count.
| For each user-user pair, return the specified similarity measure,
along with co_raters_count. | [
"For",
"each",
"user",
"-",
"user",
"pair",
"return",
"the",
"specified",
"similarity",
"measure",
"along",
"with",
"co_raters_count",
"."
] | def calcSim(user_pair,rating_pairs):
sum_xx, sum_xy, sum_yy, sum_x, sum_y, n = (0.0, 0.0, 0.0, 0.0, 0.0, 0)
for rating_pair in rating_pairs:
sum_xx += np.float(rating_pair[0]) * np.float(rating_pair[0])
sum_yy += np.float(rating_pair[1]) * np.float(rating_pair[1])
sum_xy += np.float(rati... | [
"def",
"calcSim",
"(",
"user_pair",
",",
"rating_pairs",
")",
":",
"sum_xx",
",",
"sum_xy",
",",
"sum_yy",
",",
"sum_x",
",",
"sum_y",
",",
"n",
"=",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0",
")",
"for",
"rating_pair",
... | For each user-user pair, return the specified similarity measure,
along with co_raters_count. | [
"For",
"each",
"user",
"-",
"user",
"pair",
"return",
"the",
"specified",
"similarity",
"measure",
"along",
"with",
"co_raters_count",
"."
] | [
"''' \n For each user-user pair, return the specified similarity measure,\n along with co_raters_count.\n '''",
"# sum_y += rt[1]",
"# sum_x += rt[0]"
] | [
{
"param": "user_pair",
"type": null
},
{
"param": "rating_pairs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "user_pair",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "rating_pairs",
"type": null,
"docstring": null,
"docstri... |
7d681de9615cdffe73d39618dd56bed96461551b | OCEChain/KNN | algorithms/itemBasedRecommender.py | [
"MIT"
] | Python | sampleInteractions | <not_specific> | def sampleInteractions(user_id,items_with_rating,n):
'''
For users with # interactions > n, replace their interaction history
with a sample of n items_with_rating
'''
if len(items_with_rating) > n:
return user_id, random.sample(items_with_rating,n)
else:
return user_id, items_wit... |
For users with # interactions > n, replace their interaction history
with a sample of n items_with_rating
| For users with # interactions > n, replace their interaction history
with a sample of n items_with_rating | [
"For",
"users",
"with",
"#",
"interactions",
">",
"n",
"replace",
"their",
"interaction",
"history",
"with",
"a",
"sample",
"of",
"n",
"items_with_rating"
] | def sampleInteractions(user_id,items_with_rating,n):
if len(items_with_rating) > n:
return user_id, random.sample(items_with_rating,n)
else:
return user_id, items_with_rating | [
"def",
"sampleInteractions",
"(",
"user_id",
",",
"items_with_rating",
",",
"n",
")",
":",
"if",
"len",
"(",
"items_with_rating",
")",
">",
"n",
":",
"return",
"user_id",
",",
"random",
".",
"sample",
"(",
"items_with_rating",
",",
"n",
")",
"else",
":",
... | For users with # interactions > n, replace their interaction history
with a sample of n items_with_rating | [
"For",
"users",
"with",
"#",
"interactions",
">",
"n",
"replace",
"their",
"interaction",
"history",
"with",
"a",
"sample",
"of",
"n",
"items_with_rating"
] | [
"'''\n For users with # interactions > n, replace their interaction history\n with a sample of n items_with_rating\n '''"
] | [
{
"param": "user_id",
"type": null
},
{
"param": "items_with_rating",
"type": null
},
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "user_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "items_with_rating",
"type": null,
"docstring": null,
"docs... |
7d681de9615cdffe73d39618dd56bed96461551b | OCEChain/KNN | algorithms/itemBasedRecommender.py | [
"MIT"
] | Python | keyOnFirstItem | <not_specific> | def keyOnFirstItem(item_pair,item_sim_data):
'''
For each item-item pair, make the first item's id the key
'''
(item1_id,item2_id) = item_pair
return item1_id,(item2_id,item_sim_data) |
For each item-item pair, make the first item's id the key
| For each item-item pair, make the first item's id the key | [
"For",
"each",
"item",
"-",
"item",
"pair",
"make",
"the",
"first",
"item",
"'",
"s",
"id",
"the",
"key"
] | def keyOnFirstItem(item_pair,item_sim_data):
(item1_id,item2_id) = item_pair
return item1_id,(item2_id,item_sim_data) | [
"def",
"keyOnFirstItem",
"(",
"item_pair",
",",
"item_sim_data",
")",
":",
"(",
"item1_id",
",",
"item2_id",
")",
"=",
"item_pair",
"return",
"item1_id",
",",
"(",
"item2_id",
",",
"item_sim_data",
")"
] | For each item-item pair, make the first item's id the key | [
"For",
"each",
"item",
"-",
"item",
"pair",
"make",
"the",
"first",
"item",
"'",
"s",
"id",
"the",
"key"
] | [
"'''\n For each item-item pair, make the first item's id the key\n '''"
] | [
{
"param": "item_pair",
"type": null
},
{
"param": "item_sim_data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "item_pair",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "item_sim_data",
"type": null,
"docstring": null,
"docstr... |
7d681de9615cdffe73d39618dd56bed96461551b | OCEChain/KNN | algorithms/itemBasedRecommender.py | [
"MIT"
] | Python | nearestNeighbors | <not_specific> | def nearestNeighbors(item_id,items_and_sims,n):
'''
Sort the predictions list by similarity and select the top-N neighbors
'''
items_and_sims.sort(key=lambda x: x[1][0],reverse=True)
return item_id, items_and_sims[:n] |
Sort the predictions list by similarity and select the top-N neighbors
| Sort the predictions list by similarity and select the top-N neighbors | [
"Sort",
"the",
"predictions",
"list",
"by",
"similarity",
"and",
"select",
"the",
"top",
"-",
"N",
"neighbors"
] | def nearestNeighbors(item_id,items_and_sims,n):
items_and_sims.sort(key=lambda x: x[1][0],reverse=True)
return item_id, items_and_sims[:n] | [
"def",
"nearestNeighbors",
"(",
"item_id",
",",
"items_and_sims",
",",
"n",
")",
":",
"items_and_sims",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"reverse",
"=",
"True",
")",
"return",
"item_id",
",",
... | Sort the predictions list by similarity and select the top-N neighbors | [
"Sort",
"the",
"predictions",
"list",
"by",
"similarity",
"and",
"select",
"the",
"top",
"-",
"N",
"neighbors"
] | [
"'''\n Sort the predictions list by similarity and select the top-N neighbors\n '''"
] | [
{
"param": "item_id",
"type": null
},
{
"param": "items_and_sims",
"type": null
},
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "item_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "items_and_sims",
"type": null,
"docstring": null,
"docstri... |
7d681de9615cdffe73d39618dd56bed96461551b | OCEChain/KNN | algorithms/itemBasedRecommender.py | [
"MIT"
] | Python | topNRecommendations | <not_specific> | def topNRecommendations(user_id,items_with_rating,item_sims,n):
'''
Calculate the top-N item recommendations for each user using the
weighted sums method
'''
# initialize dicts to store the score of each individual item,
# since an item can exist in more than one item neighborhood
totals =... |
Calculate the top-N item recommendations for each user using the
weighted sums method
| Calculate the top-N item recommendations for each user using the
weighted sums method | [
"Calculate",
"the",
"top",
"-",
"N",
"item",
"recommendations",
"for",
"each",
"user",
"using",
"the",
"weighted",
"sums",
"method"
] | def topNRecommendations(user_id,items_with_rating,item_sims,n):
totals = defaultdict(int)
sim_sums = defaultdict(int)
for (item,rating) in items_with_rating:
nearest_neighbors = item_sims.get(item,None)
if nearest_neighbors:
for (neighbor,(sim,count)) in nearest_neighbors:
... | [
"def",
"topNRecommendations",
"(",
"user_id",
",",
"items_with_rating",
",",
"item_sims",
",",
"n",
")",
":",
"totals",
"=",
"defaultdict",
"(",
"int",
")",
"sim_sums",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"(",
"item",
",",
"rating",
")",
"in",
"i... | Calculate the top-N item recommendations for each user using the
weighted sums method | [
"Calculate",
"the",
"top",
"-",
"N",
"item",
"recommendations",
"for",
"each",
"user",
"using",
"the",
"weighted",
"sums",
"method"
] | [
"'''\n Calculate the top-N item recommendations for each user using the \n weighted sums method\n '''",
"# initialize dicts to store the score of each individual item,",
"# since an item can exist in more than one item neighborhood",
"# lookup the nearest neighbors for this item",
"# update totals ... | [
{
"param": "user_id",
"type": null
},
{
"param": "items_with_rating",
"type": null
},
{
"param": "item_sims",
"type": null
},
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "user_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "items_with_rating",
"type": null,
"docstring": null,
"docs... |
e71c4cf4a8de47ce37f7ca6981eab5c16eb1805f | ikondov/fireworks_schema | fireworks_schema/tests/fw_serializers_test.py | [
"BSD-3-Clause"
] | Python | _validate_from_file | null | def _validate_from_file(self, module, classname):
""" validate a set of samples against the schema via from_file() """
namespace = __import__(module.split('.')[0])
for subpackage in module.split('.')[1:]:
namespace = getattr(namespace, subpackage)
cls = getattr(namespace, cla... | validate a set of samples against the schema via from_file() | validate a set of samples against the schema via from_file() | [
"validate",
"a",
"set",
"of",
"samples",
"against",
"the",
"schema",
"via",
"from_file",
"()"
] | def _validate_from_file(self, module, classname):
namespace = __import__(module.split('.')[0])
for subpackage in module.split('.')[1:]:
namespace = getattr(namespace, subpackage)
cls = getattr(namespace, classname)
path = os.path.join(SAMPLES_DIR, classname.lower())
f... | [
"def",
"_validate_from_file",
"(",
"self",
",",
"module",
",",
"classname",
")",
":",
"namespace",
"=",
"__import__",
"(",
"module",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"for",
"subpackage",
"in",
"module",
".",
"split",
"(",
"'.'",
")",
... | validate a set of samples against the schema via from_file() | [
"validate",
"a",
"set",
"of",
"samples",
"against",
"the",
"schema",
"via",
"from_file",
"()"
] | [
"\"\"\" validate a set of samples against the schema via from_file() \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "module",
"type": null
},
{
"param": "classname",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "module",
"type": null,
"docstring": null,
"docstring_tokens":... |
803fed05149813f736152a56f18237a8ade8ba2c | ikondov/fireworks_schema | fireworks_schema/json_schema.py | [
"BSD-3-Clause"
] | Python | validate | null | def validate(instance, schema_name):
""" JSON schema validator working with relative paths """
schema_file = schema_name.lower() + '.json'
schema_path = os.path.join(SCHEMA_DIR, schema_file)
with open(schema_path, 'rt') as fileh:
schema_dict = json.load(fileh)
base_uri = Path(os.path.abspath... | JSON schema validator working with relative paths | JSON schema validator working with relative paths | [
"JSON",
"schema",
"validator",
"working",
"with",
"relative",
"paths"
] | def validate(instance, schema_name):
schema_file = schema_name.lower() + '.json'
schema_path = os.path.join(SCHEMA_DIR, schema_file)
with open(schema_path, 'rt') as fileh:
schema_dict = json.load(fileh)
base_uri = Path(os.path.abspath(schema_path)).as_uri()
custom_res = jsonschema.RefResolve... | [
"def",
"validate",
"(",
"instance",
",",
"schema_name",
")",
":",
"schema_file",
"=",
"schema_name",
".",
"lower",
"(",
")",
"+",
"'.json'",
"schema_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SCHEMA_DIR",
",",
"schema_file",
")",
"with",
"open",
"... | JSON schema validator working with relative paths | [
"JSON",
"schema",
"validator",
"working",
"with",
"relative",
"paths"
] | [
"\"\"\" JSON schema validator working with relative paths \"\"\""
] | [
{
"param": "instance",
"type": null
},
{
"param": "schema_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "instance",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "schema_name",
"type": null,
"docstring": null,
"docstring... |
be139fc9ed8a5ae838f5e75c24d8ae5f6149983b | gourie/training_RL | dqn.py | [
"BSD-3-Clause"
] | Python | buildModel | null | def buildModel(self, inputSize=21168):
""" Build regression modeol that minimizes using qTarget (satisfying Bellman eq using current weights) - predictQ, train using Adam to find optimal W
Args:
inputSize: length of list provided as input
Returns:
None, updates the list ... | Build regression modeol that minimizes using qTarget (satisfying Bellman eq using current weights) - predictQ, train using Adam to find optimal W
Args:
inputSize: length of list provided as input
Returns:
None, updates the list of variables collected in the graph under the key ... | Build regression modeol that minimizes using qTarget (satisfying Bellman eq using current weights) - predictQ, train using Adam to find optimal W
Args:
inputSize: length of list provided as input
Returns:
None, updates the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES.
Raises:
Non... | [
"Build",
"regression",
"modeol",
"that",
"minimizes",
"using",
"qTarget",
"(",
"satisfying",
"Bellman",
"eq",
"using",
"current",
"weights",
")",
"-",
"predictQ",
"train",
"using",
"Adam",
"to",
"find",
"optimal",
"W",
"Args",
":",
"inputSize",
":",
"length",
... | def buildModel(self, inputSize=21168):
self.input_data = tf.placeholder(shape=[None,inputSize], dtype=tf.float32)
l1_output = tf.contrib.layers.conv2d(inputs=tf.reshape(self.input_data, shape=[-1, 84, 84, 3]), num_outputs=self.conv_layer1['filters'],
kernel_size=[sel... | [
"def",
"buildModel",
"(",
"self",
",",
"inputSize",
"=",
"21168",
")",
":",
"self",
".",
"input_data",
"=",
"tf",
".",
"placeholder",
"(",
"shape",
"=",
"[",
"None",
",",
"inputSize",
"]",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"l1_output",
"=... | Build regression modeol that minimizes using qTarget (satisfying Bellman eq using current weights) - predictQ, train using Adam to find optimal W
Args:
inputSize: length of list provided as input
Returns:
None, updates the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. | [
"Build",
"regression",
"modeol",
"that",
"minimizes",
"using",
"qTarget",
"(",
"satisfying",
"Bellman",
"eq",
"using",
"current",
"weights",
")",
"-",
"predictQ",
"train",
"using",
"Adam",
"to",
"find",
"optimal",
"W",
"Args",
":",
"inputSize",
":",
"length",
... | [
"\"\"\" Build regression modeol that minimizes using qTarget (satisfying Bellman eq using current weights) - predictQ, train using Adam to find optimal W\n Args:\n inputSize: length of list provided as input\n Returns:\n None, updates the list of variables collected in the graph... | [
{
"param": "self",
"type": null
},
{
"param": "inputSize",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "inputSize",
"type": null,
"docstring": null,
"docstring_token... |
27f24a7813c3b3bdbd04a786a70a6d5e936ee7e9 | gourie/training_RL | gridworld.py | [
"BSD-3-Clause"
] | Python | processState | <not_specific> | def processState(states):
"""
Returns the game states 84x84x3 in a flattened array of shape (21168,1)
:param states: game states, 84x84x3 array
:return:
"""
return np.reshape(states,[21168]) |
Returns the game states 84x84x3 in a flattened array of shape (21168,1)
:param states: game states, 84x84x3 array
:return:
| Returns the game states 84x84x3 in a flattened array of shape (21168,1) | [
"Returns",
"the",
"game",
"states",
"84x84x3",
"in",
"a",
"flattened",
"array",
"of",
"shape",
"(",
"21168",
"1",
")"
] | def processState(states):
return np.reshape(states,[21168]) | [
"def",
"processState",
"(",
"states",
")",
":",
"return",
"np",
".",
"reshape",
"(",
"states",
",",
"[",
"21168",
"]",
")"
] | Returns the game states 84x84x3 in a flattened array of shape (21168,1) | [
"Returns",
"the",
"game",
"states",
"84x84x3",
"in",
"a",
"flattened",
"array",
"of",
"shape",
"(",
"21168",
"1",
")"
] | [
"\"\"\"\n Returns the game states 84x84x3 in a flattened array of shape (21168,1)\n :param states: game states, 84x84x3 array\n :return:\n \"\"\""
] | [
{
"param": "states",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "states",
"type": null,
"docstring": "game states, 84x84x3 array",
"docstring_tokens": [
"game",
"st... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | _patched_convert_scalar_field_value | null | def _patched_convert_scalar_field_value():
"""Temporarily patch the scalar field conversion function."""
convert_scalar_field_value_func = json_format._ConvertScalarFieldValue # type: ignore[attr-defined]
json_format._ConvertScalarFieldValue = _handle_bytes( # type: ignore[attr-defined]
json_forma... | Temporarily patch the scalar field conversion function. | Temporarily patch the scalar field conversion function. | [
"Temporarily",
"patch",
"the",
"scalar",
"field",
"conversion",
"function",
"."
] | def _patched_convert_scalar_field_value():
convert_scalar_field_value_func = json_format._ConvertScalarFieldValue
json_format._ConvertScalarFieldValue = _handle_bytes(
json_format._ConvertScalarFieldValue
)
try:
yield
finally:
json_format._ConvertScalarFieldValue = conv... | [
"def",
"_patched_convert_scalar_field_value",
"(",
")",
":",
"convert_scalar_field_value_func",
"=",
"json_format",
".",
"_ConvertScalarFieldValue",
"json_format",
".",
"_ConvertScalarFieldValue",
"=",
"_handle_bytes",
"(",
"json_format",
".",
"_ConvertScalarFieldValue",
")",
... | Temporarily patch the scalar field conversion function. | [
"Temporarily",
"patch",
"the",
"scalar",
"field",
"conversion",
"function",
"."
] | [
"\"\"\"Temporarily patch the scalar field conversion function.\"\"\"",
"# type: ignore[attr-defined]",
"# type: ignore[attr-defined]",
"# type: ignore[attr-defined]"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | register_serializer | null | def register_serializer(
self,
message: t.Type[Message],
serializer: t.Callable,
return_type: DataType,
):
"""Map a message type to a custom serializer and spark output type.
The serializer should be a function which returns an object which
can be coerced int... | Map a message type to a custom serializer and spark output type.
The serializer should be a function which returns an object which
can be coerced into the spark return type.
| Map a message type to a custom serializer and spark output type.
The serializer should be a function which returns an object which
can be coerced into the spark return type. | [
"Map",
"a",
"message",
"type",
"to",
"a",
"custom",
"serializer",
"and",
"spark",
"output",
"type",
".",
"The",
"serializer",
"should",
"be",
"a",
"function",
"which",
"returns",
"an",
"object",
"which",
"can",
"be",
"coerced",
"into",
"the",
"spark",
"ret... | def register_serializer(
self,
message: t.Type[Message],
serializer: t.Callable,
return_type: DataType,
):
full_name = message.DESCRIPTOR.full_name
self._custom_serializers[full_name] = serializer
self._message_type_to_spark_type_map[full_name] = return_type | [
"def",
"register_serializer",
"(",
"self",
",",
"message",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"serializer",
":",
"t",
".",
"Callable",
",",
"return_type",
":",
"DataType",
",",
")",
":",
"full_name",
"=",
"message",
".",
"DESCRIPTOR",
".",
... | Map a message type to a custom serializer and spark output type. | [
"Map",
"a",
"message",
"type",
"to",
"a",
"custom",
"serializer",
"and",
"spark",
"output",
"type",
"."
] | [
"\"\"\"Map a message type to a custom serializer and spark output type.\n\n The serializer should be a function which returns an object which\n can be coerced into the spark return type.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "message",
"type": "t.Type[Message]"
},
{
"param": "serializer",
"type": "t.Callable"
},
{
"param": "return_type",
"type": "DataType"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message",
"type": "t.Type[Message]",
"docstring": null,
"docs... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | message_to_dict | <not_specific> | def message_to_dict(
self,
message: Message,
including_default_value_fields=False,
preserving_proto_field_name=False,
use_integers_for_enums=False,
descriptor_pool=None,
float_precision=None,
):
"""Custom MessageToDict using overridden printer."""
... | Custom MessageToDict using overridden printer. | Custom MessageToDict using overridden printer. | [
"Custom",
"MessageToDict",
"using",
"overridden",
"printer",
"."
] | def message_to_dict(
self,
message: Message,
including_default_value_fields=False,
preserving_proto_field_name=False,
use_integers_for_enums=False,
descriptor_pool=None,
float_precision=None,
):
printer = _Printer(
custom_serializers=self._... | [
"def",
"message_to_dict",
"(",
"self",
",",
"message",
":",
"Message",
",",
"including_default_value_fields",
"=",
"False",
",",
"preserving_proto_field_name",
"=",
"False",
",",
"use_integers_for_enums",
"=",
"False",
",",
"descriptor_pool",
"=",
"None",
",",
"floa... | Custom MessageToDict using overridden printer. | [
"Custom",
"MessageToDict",
"using",
"overridden",
"printer",
"."
] | [
"\"\"\"Custom MessageToDict using overridden printer.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "message",
"type": "Message"
},
{
"param": "including_default_value_fields",
"type": null
},
{
"param": "preserving_proto_field_name",
"type": null
},
{
"param": "use_integers_for_enums",
"type": null
},
{
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message",
"type": "Message",
"docstring": null,
"docstring_to... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | parse_dict | <not_specific> | def parse_dict(
self,
value: dict,
message: Message,
ignore_unknown_fields: bool = False,
descriptor_pool: t.Optional[DescriptorPool] = None,
max_recursion_depth: int = 100,
):
"""Custom ParseDict using overridden parser."""
parser = _Parser(
... | Custom ParseDict using overridden parser. | Custom ParseDict using overridden parser. | [
"Custom",
"ParseDict",
"using",
"overridden",
"parser",
"."
] | def parse_dict(
self,
value: dict,
message: Message,
ignore_unknown_fields: bool = False,
descriptor_pool: t.Optional[DescriptorPool] = None,
max_recursion_depth: int = 100,
):
parser = _Parser(
custom_deserializers=self._custom_deserializers,
... | [
"def",
"parse_dict",
"(",
"self",
",",
"value",
":",
"dict",
",",
"message",
":",
"Message",
",",
"ignore_unknown_fields",
":",
"bool",
"=",
"False",
",",
"descriptor_pool",
":",
"t",
".",
"Optional",
"[",
"DescriptorPool",
"]",
"=",
"None",
",",
"max_recu... | Custom ParseDict using overridden parser. | [
"Custom",
"ParseDict",
"using",
"overridden",
"parser",
"."
] | [
"\"\"\"Custom ParseDict using overridden parser.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": "dict"
},
{
"param": "message",
"type": "Message"
},
{
"param": "ignore_unknown_fields",
"type": "bool"
},
{
"param": "descriptor_pool",
"type": "t.Optional[DescriptorPool]"
},
{
"param": "... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "value",
"type": "dict",
"docstring": null,
"docstring_tokens"... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | from_protobuf | Column | def from_protobuf(
self,
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
) -> Column:
"""Deserialize protobuf messages to spark structs.
Given a column and protobuf message type, deserialize
protobuf messages also ... | Deserialize protobuf messages to spark structs.
Given a column and protobuf message type, deserialize
protobuf messages also using our custom serializers.
The ``options`` arg should be a dictionary for the kwargs passed
our message_to_dict (same args as protobuf's MessageToDict).
... | Deserialize protobuf messages to spark structs.
Given a column and protobuf message type, deserialize
protobuf messages also using our custom serializers.
The ``options`` arg should be a dictionary for the kwargs passed
our message_to_dict (same args as protobuf's MessageToDict). | [
"Deserialize",
"protobuf",
"messages",
"to",
"spark",
"structs",
".",
"Given",
"a",
"column",
"and",
"protobuf",
"message",
"type",
"deserialize",
"protobuf",
"messages",
"also",
"using",
"our",
"custom",
"serializers",
".",
"The",
"`",
"`",
"options",
"`",
"`... | def from_protobuf(
self,
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
) -> Column:
column = col(data) if isinstance(data, str) else data
protobuf_decoder_udf = self.get_decoder_udf(message_type, options)
return p... | [
"def",
"from_protobuf",
"(",
"self",
",",
"data",
":",
"t",
".",
"Union",
"[",
"Column",
",",
"str",
"]",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
"... | Deserialize protobuf messages to spark structs. | [
"Deserialize",
"protobuf",
"messages",
"to",
"spark",
"structs",
"."
] | [
"\"\"\"Deserialize protobuf messages to spark structs.\n\n Given a column and protobuf message type, deserialize\n protobuf messages also using our custom serializers.\n\n The ``options`` arg should be a dictionary for the kwargs passed\n our message_to_dict (same args as protobuf's Mess... | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": "t.Union[Column, str]"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": "t.Union[Column, str]",
"docstring": null,
"do... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | to_protobuf | Column | def to_protobuf(
self,
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
) -> Column:
"""Serialize spark structs to protobuf messages.
Given a column and protobuf message type, serialize
protobuf messages also using ... | Serialize spark structs to protobuf messages.
Given a column and protobuf message type, serialize
protobuf messages also using our custom serializers.
The ``options`` arg should be a dictionary for the kwargs passed
our parse_dict (same args as protobuf's ParseDict).
| Serialize spark structs to protobuf messages.
Given a column and protobuf message type, serialize
protobuf messages also using our custom serializers.
The ``options`` arg should be a dictionary for the kwargs passed
our parse_dict (same args as protobuf's ParseDict). | [
"Serialize",
"spark",
"structs",
"to",
"protobuf",
"messages",
".",
"Given",
"a",
"column",
"and",
"protobuf",
"message",
"type",
"serialize",
"protobuf",
"messages",
"also",
"using",
"our",
"custom",
"serializers",
".",
"The",
"`",
"`",
"options",
"`",
"`",
... | def to_protobuf(
self,
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
) -> Column:
column = col(data) if isinstance(data, str) else data
protobuf_encoder_udf = self.get_encoder_udf(message_type, options)
return pro... | [
"def",
"to_protobuf",
"(",
"self",
",",
"data",
":",
"t",
".",
"Union",
"[",
"Column",
",",
"str",
"]",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
","... | Serialize spark structs to protobuf messages. | [
"Serialize",
"spark",
"structs",
"to",
"protobuf",
"messages",
"."
] | [
"\"\"\"Serialize spark structs to protobuf messages.\n\n Given a column and protobuf message type, serialize\n protobuf messages also using our custom serializers.\n\n The ``options`` arg should be a dictionary for the kwargs passed\n our parse_dict (same args as protobuf's ParseDict).\n... | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": "t.Union[Column, str]"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": "t.Union[Column, str]",
"docstring": null,
"do... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | df_from_protobuf | DataFrame | def df_from_protobuf(
self,
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
) -> DataFrame:
"""Decode a dataframe of encoded protobuf.
If expanded, return a dataframe in which each field is its own colum... | Decode a dataframe of encoded protobuf.
If expanded, return a dataframe in which each field is its own column. Otherwise
return a dataframe with a single struct column named `value`.
| Decode a dataframe of encoded protobuf.
If expanded, return a dataframe in which each field is its own column. Otherwise
return a dataframe with a single struct column named `value`. | [
"Decode",
"a",
"dataframe",
"of",
"encoded",
"protobuf",
".",
"If",
"expanded",
"return",
"a",
"dataframe",
"in",
"which",
"each",
"field",
"is",
"its",
"own",
"column",
".",
"Otherwise",
"return",
"a",
"dataframe",
"with",
"a",
"single",
"struct",
"column",... | def df_from_protobuf(
self,
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
) -> DataFrame:
df_decoded = df.select(
self.from_protobuf(df.columns[0], message_type, options).alias("value")
)
... | [
"def",
"df_from_protobuf",
"(",
"self",
",",
"df",
":",
"DataFrame",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"expanded",
":",
"bool",
"=",
"False"... | Decode a dataframe of encoded protobuf. | [
"Decode",
"a",
"dataframe",
"of",
"encoded",
"protobuf",
"."
] | [
"\"\"\"Decode a dataframe of encoded protobuf.\n\n If expanded, return a dataframe in which each field is its own column. Otherwise\n return a dataframe with a single struct column named `value`.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "df",
"type": "DataFrame"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
},
{
"param": "expanded",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "df",
"type": "DataFrame",
"docstring": null,
"docstring_token... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | df_to_protobuf | DataFrame | def df_to_protobuf(
self,
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
) -> DataFrame:
"""Encode data in a dataframe to protobuf as column `value`.
If `expanded`, the passed dataframe columns will be ... | Encode data in a dataframe to protobuf as column `value`.
If `expanded`, the passed dataframe columns will be packed into a struct before
converting. Otherwise it is assumed that the dataframe passed is a single column
of data already packed into a struct.
Returns a dataframe with a si... | Encode data in a dataframe to protobuf as column `value`.
If `expanded`, the passed dataframe columns will be packed into a struct before
converting. Otherwise it is assumed that the dataframe passed is a single column
of data already packed into a struct.
Returns a dataframe with a single column named `value` contain... | [
"Encode",
"data",
"in",
"a",
"dataframe",
"to",
"protobuf",
"as",
"column",
"`",
"value",
"`",
".",
"If",
"`",
"expanded",
"`",
"the",
"passed",
"dataframe",
"columns",
"will",
"be",
"packed",
"into",
"a",
"struct",
"before",
"converting",
".",
"Otherwise"... | def df_to_protobuf(
self,
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
) -> DataFrame:
if expanded:
df_struct = df.select(
struct([df[c] for c in df.columns]).alias("value")
... | [
"def",
"df_to_protobuf",
"(",
"self",
",",
"df",
":",
"DataFrame",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"expanded",
":",
"bool",
"=",
"False",
... | Encode data in a dataframe to protobuf as column `value`. | [
"Encode",
"data",
"in",
"a",
"dataframe",
"to",
"protobuf",
"as",
"column",
"`",
"value",
"`",
"."
] | [
"\"\"\"Encode data in a dataframe to protobuf as column `value`.\n\n If `expanded`, the passed dataframe columns will be packed into a struct before\n converting. Otherwise it is assumed that the dataframe passed is a single column\n of data already packed into a struct.\n\n Returns a da... | [
{
"param": "self",
"type": null
},
{
"param": "df",
"type": "DataFrame"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
},
{
"param": "expanded",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "df",
"type": "DataFrame",
"docstring": null,
"docstring_token... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | from_protobuf | Column | def from_protobuf(
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
mc: MessageConverter = None,
) -> Column:
"""Deserialize protobuf messages to spark structs"""
mc = mc or MessageConverter()
return mc.from_protobuf(data=data, message_type=message... | Deserialize protobuf messages to spark structs | Deserialize protobuf messages to spark structs | [
"Deserialize",
"protobuf",
"messages",
"to",
"spark",
"structs"
] | def from_protobuf(
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
mc: MessageConverter = None,
) -> Column:
mc = mc or MessageConverter()
return mc.from_protobuf(data=data, message_type=message_type, options=options) | [
"def",
"from_protobuf",
"(",
"data",
":",
"t",
".",
"Union",
"[",
"Column",
",",
"str",
"]",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"mc",
":"... | Deserialize protobuf messages to spark structs | [
"Deserialize",
"protobuf",
"messages",
"to",
"spark",
"structs"
] | [
"\"\"\"Deserialize protobuf messages to spark structs\"\"\""
] | [
{
"param": "data",
"type": "t.Union[Column, str]"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
},
{
"param": "mc",
"type": "MessageConverter"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": "t.Union[Column, str]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message_type",
"type": "t.Type[Message]",
"docstr... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | to_protobuf | Column | def to_protobuf(
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
mc: MessageConverter = None,
) -> Column:
"""Serialize spark structs to protobuf messages."""
mc = mc or MessageConverter()
return mc.to_protobuf(data=data, message_type=message_type... | Serialize spark structs to protobuf messages. | Serialize spark structs to protobuf messages. | [
"Serialize",
"spark",
"structs",
"to",
"protobuf",
"messages",
"."
] | def to_protobuf(
data: t.Union[Column, str],
message_type: t.Type[Message],
options: t.Optional[dict] = None,
mc: MessageConverter = None,
) -> Column:
mc = mc or MessageConverter()
return mc.to_protobuf(data=data, message_type=message_type, options=options) | [
"def",
"to_protobuf",
"(",
"data",
":",
"t",
".",
"Union",
"[",
"Column",
",",
"str",
"]",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"mc",
":",
... | Serialize spark structs to protobuf messages. | [
"Serialize",
"spark",
"structs",
"to",
"protobuf",
"messages",
"."
] | [
"\"\"\"Serialize spark structs to protobuf messages.\"\"\""
] | [
{
"param": "data",
"type": "t.Union[Column, str]"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
},
{
"param": "mc",
"type": "MessageConverter"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": "t.Union[Column, str]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message_type",
"type": "t.Type[Message]",
"docstr... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | df_from_protobuf | DataFrame | def df_from_protobuf(
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
mc: MessageConverter = None,
) -> DataFrame:
"""Decode a dataframe of encoded protobuf.
If expanded, return a dataframe in which each field is its own column. Otherw... | Decode a dataframe of encoded protobuf.
If expanded, return a dataframe in which each field is its own column. Otherwise
return a dataframe with a single struct column named `value`.
| Decode a dataframe of encoded protobuf.
If expanded, return a dataframe in which each field is its own column. Otherwise
return a dataframe with a single struct column named `value`. | [
"Decode",
"a",
"dataframe",
"of",
"encoded",
"protobuf",
".",
"If",
"expanded",
"return",
"a",
"dataframe",
"in",
"which",
"each",
"field",
"is",
"its",
"own",
"column",
".",
"Otherwise",
"return",
"a",
"dataframe",
"with",
"a",
"single",
"struct",
"column",... | def df_from_protobuf(
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
mc: MessageConverter = None,
) -> DataFrame:
mc = mc or MessageConverter()
return mc.df_from_protobuf(
df=df, message_type=message_type, options=options, expa... | [
"def",
"df_from_protobuf",
"(",
"df",
":",
"DataFrame",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"expanded",
":",
"bool",
"=",
"False",
",",
"mc",
... | Decode a dataframe of encoded protobuf. | [
"Decode",
"a",
"dataframe",
"of",
"encoded",
"protobuf",
"."
] | [
"\"\"\"Decode a dataframe of encoded protobuf.\n\n If expanded, return a dataframe in which each field is its own column. Otherwise\n return a dataframe with a single struct column named `value`.\n \"\"\""
] | [
{
"param": "df",
"type": "DataFrame"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
},
{
"param": "expanded",
"type": "bool"
},
{
"param": "mc",
"type": "MessageConverter"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": "DataFrame",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message_type",
"type": "t.Type[Message]",
"docstring": null,
... |
2657ed6b094a00d06e59df4f66e98492967d01ec | crflynn/pbspark | pbspark/_proto.py | [
"MIT"
] | Python | df_to_protobuf | DataFrame | def df_to_protobuf(
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
mc: MessageConverter = None,
) -> DataFrame:
"""Encode data in a dataframe to protobuf as column `value`.
If `expanded`, the passed dataframe columns will be packed in... | Encode data in a dataframe to protobuf as column `value`.
If `expanded`, the passed dataframe columns will be packed into a struct before
converting. Otherwise it is assumed that the dataframe passed is a single column
of data already packed into a struct.
Returns a dataframe with a single column name... | Encode data in a dataframe to protobuf as column `value`.
If `expanded`, the passed dataframe columns will be packed into a struct before
converting. Otherwise it is assumed that the dataframe passed is a single column
of data already packed into a struct.
Returns a dataframe with a single column named `value` contain... | [
"Encode",
"data",
"in",
"a",
"dataframe",
"to",
"protobuf",
"as",
"column",
"`",
"value",
"`",
".",
"If",
"`",
"expanded",
"`",
"the",
"passed",
"dataframe",
"columns",
"will",
"be",
"packed",
"into",
"a",
"struct",
"before",
"converting",
".",
"Otherwise"... | def df_to_protobuf(
df: DataFrame,
message_type: t.Type[Message],
options: t.Optional[dict] = None,
expanded: bool = False,
mc: MessageConverter = None,
) -> DataFrame:
mc = mc or MessageConverter()
return mc.df_to_protobuf(
df=df, message_type=message_type, options=options, expanded... | [
"def",
"df_to_protobuf",
"(",
"df",
":",
"DataFrame",
",",
"message_type",
":",
"t",
".",
"Type",
"[",
"Message",
"]",
",",
"options",
":",
"t",
".",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"expanded",
":",
"bool",
"=",
"False",
",",
"mc",
... | Encode data in a dataframe to protobuf as column `value`. | [
"Encode",
"data",
"in",
"a",
"dataframe",
"to",
"protobuf",
"as",
"column",
"`",
"value",
"`",
"."
] | [
"\"\"\"Encode data in a dataframe to protobuf as column `value`.\n\n If `expanded`, the passed dataframe columns will be packed into a struct before\n converting. Otherwise it is assumed that the dataframe passed is a single column\n of data already packed into a struct.\n\n Returns a dataframe with a s... | [
{
"param": "df",
"type": "DataFrame"
},
{
"param": "message_type",
"type": "t.Type[Message]"
},
{
"param": "options",
"type": "t.Optional[dict]"
},
{
"param": "expanded",
"type": "bool"
},
{
"param": "mc",
"type": "MessageConverter"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": "DataFrame",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message_type",
"type": "t.Type[Message]",
"docstring": null,
... |
dc27fc48f5cd0a299bd06514f54240f790964ce5 | crflynn/pbspark | pbspark/_timestamp.py | [
"MIT"
] | Python | _to_datetime | datetime.datetime | def _to_datetime(message: Timestamp) -> datetime.datetime:
"""Convert a Timestamp to a python datetime."""
return well_known_types._EPOCH_DATETIME_NAIVE + datetime.timedelta( # type: ignore[attr-defined]
seconds=message.seconds,
microseconds=well_known_types._RoundTowardZero( # type: ignore[at... | Convert a Timestamp to a python datetime. | Convert a Timestamp to a python datetime. | [
"Convert",
"a",
"Timestamp",
"to",
"a",
"python",
"datetime",
"."
] | def _to_datetime(message: Timestamp) -> datetime.datetime:
return well_known_types._EPOCH_DATETIME_NAIVE + datetime.timedelta(
seconds=message.seconds,
microseconds=well_known_types._RoundTowardZero(
message.nanos,
well_known_types._NANOS_PER_MICROSECOND,
),
... | [
"def",
"_to_datetime",
"(",
"message",
":",
"Timestamp",
")",
"->",
"datetime",
".",
"datetime",
":",
"return",
"well_known_types",
".",
"_EPOCH_DATETIME_NAIVE",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"message",
".",
"seconds",
",",
"microsecond... | Convert a Timestamp to a python datetime. | [
"Convert",
"a",
"Timestamp",
"to",
"a",
"python",
"datetime",
"."
] | [
"\"\"\"Convert a Timestamp to a python datetime.\"\"\"",
"# type: ignore[attr-defined]",
"# type: ignore[attr-defined]",
"# type: ignore[attr-defined]"
] | [
{
"param": "message",
"type": "Timestamp"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "message",
"type": "Timestamp",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
18fc3d36ba9f43c9d7369d76e4e9fa68ce8275cc | chrism0dwk/chain_binomial_rippler | chain_binomial_rippler.py | [
"MIT"
] | Python | _get_src_states | <not_specific> | def _get_src_states(stoichiometry):
"""Iterate over rows in `stoichiometry` and return
the index of the column containing a `-1`"""
src_states = tf.where(tf.math.equal(stoichiometry, -1.0))
return src_states[:, 1] | Iterate over rows in `stoichiometry` and return
the index of the column containing a `-1` | Iterate over rows in `stoichiometry` and return
the index of the column containing a `-1` | [
"Iterate",
"over",
"rows",
"in",
"`",
"stoichiometry",
"`",
"and",
"return",
"the",
"index",
"of",
"the",
"column",
"containing",
"a",
"`",
"-",
"1",
"`"
] | def _get_src_states(stoichiometry):
src_states = tf.where(tf.math.equal(stoichiometry, -1.0))
return src_states[:, 1] | [
"def",
"_get_src_states",
"(",
"stoichiometry",
")",
":",
"src_states",
"=",
"tf",
".",
"where",
"(",
"tf",
".",
"math",
".",
"equal",
"(",
"stoichiometry",
",",
"-",
"1.0",
")",
")",
"return",
"src_states",
"[",
":",
",",
"1",
"]"
] | Iterate over rows in `stoichiometry` and return
the index of the column containing a `-1` | [
"Iterate",
"over",
"rows",
"in",
"`",
"stoichiometry",
"`",
"and",
"return",
"the",
"index",
"of",
"the",
"column",
"containing",
"a",
"`",
"-",
"1",
"`"
] | [
"\"\"\"Iterate over rows in `stoichiometry` and return\n the index of the column containing a `-1`\"\"\""
] | [
{
"param": "stoichiometry",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stoichiometry",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
18fc3d36ba9f43c9d7369d76e4e9fa68ce8275cc | chrism0dwk/chain_binomial_rippler | chain_binomial_rippler.py | [
"MIT"
] | Python | _compute_state | <not_specific> | def _compute_state(initial_state, events, stoichiometry, closed=False):
"""Computes a state tensor from initial state and event tensor
:param initial_state: a tensor of shape [S, M]
:param events: a tensor of shape [T, R, M]
:param stoichiometry: a stoichiometry matrix of shape [R, S] describing
... | Computes a state tensor from initial state and event tensor
:param initial_state: a tensor of shape [S, M]
:param events: a tensor of shape [T, R, M]
:param stoichiometry: a stoichiometry matrix of shape [R, S] describing
how transitions update the state.
:param closed: if `Tr... | Computes a state tensor from initial state and event tensor | [
"Computes",
"a",
"state",
"tensor",
"from",
"initial",
"state",
"and",
"event",
"tensor"
] | def _compute_state(initial_state, events, stoichiometry, closed=False):
if isinstance(stoichiometry, tf.Tensor):
stoichiometry = ps.cast(stoichiometry, dtype=events.dtype)
else:
stoichiometry = tf.convert_to_tensor(stoichiometry, dtype=events.dtype)
increments = tf.einsum("...trm,rs->...tsm"... | [
"def",
"_compute_state",
"(",
"initial_state",
",",
"events",
",",
"stoichiometry",
",",
"closed",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"stoichiometry",
",",
"tf",
".",
"Tensor",
")",
":",
"stoichiometry",
"=",
"ps",
".",
"cast",
"(",
"stoichio... | Computes a state tensor from initial state and event tensor | [
"Computes",
"a",
"state",
"tensor",
"from",
"initial",
"state",
"and",
"event",
"tensor"
] | [
"\"\"\"Computes a state tensor from initial state and event tensor\n\n :param initial_state: a tensor of shape [S, M]\n :param events: a tensor of shape [T, R, M]\n :param stoichiometry: a stoichiometry matrix of shape [R, S] describing\n how transitions update the state.\n :par... | [
{
"param": "initial_state",
"type": null
},
{
"param": "events",
"type": null
},
{
"param": "stoichiometry",
"type": null
},
{
"param": "closed",
"type": null
}
] | {
"returns": [
{
"docstring": "a tensor of shape [T, S, M] if `closed=False` or [T+1, S, M] if `closed=True`\ndescribing the state of the\nsystem for each batch M at time T.",
"docstring_tokens": [
"a",
"tensor",
"of",
"shape",
"[",
"T",
"S",
... |
18fc3d36ba9f43c9d7369d76e4e9fa68ce8275cc | chrism0dwk/chain_binomial_rippler | chain_binomial_rippler.py | [
"MIT"
] | Python | _dispatch_update | <not_specific> | def _dispatch_update(z, x, p, xs, ps, seed=None, validate_args=False):
"""Dispatches update function based on values of
parameters.
**This is purely a scalar function due to random_hypergeom**
:param z: current $z$
:param x: current $x$
:param p: $p$ current probability
:param xs: $x^\... | Dispatches update function based on values of
parameters.
**This is purely a scalar function due to random_hypergeom**
:param z: current $z$
:param x: current $x$
:param p: $p$ current probability
:param xs: $x^\star$ new state
:param ps: $p_star$ new probability
:returns: an upda... | Dispatches update function based on values of
parameters.
This is purely a scalar function due to random_hypergeom | [
"Dispatches",
"update",
"function",
"based",
"on",
"values",
"of",
"parameters",
".",
"This",
"is",
"purely",
"a",
"scalar",
"function",
"due",
"to",
"random_hypergeom"
] | def _dispatch_update(z, x, p, xs, ps, seed=None, validate_args=False):
with tf.name_scope("dispatch_update"):
p = tf.convert_to_tensor(p)
ps = tf.convert_to_tensor(ps)
z = tf.cast(z, p.dtype)
x = tf.cast(x, p.dtype)
xs = tf.cast(xs, p.dtype)
seeds = samplers.split_see... | [
"def",
"_dispatch_update",
"(",
"z",
",",
"x",
",",
"p",
",",
"xs",
",",
"ps",
",",
"seed",
"=",
"None",
",",
"validate_args",
"=",
"False",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"dispatch_update\"",
")",
":",
"p",
"=",
"tf",
".",
"conv... | Dispatches update function based on values of
parameters. | [
"Dispatches",
"update",
"function",
"based",
"on",
"values",
"of",
"parameters",
"."
] | [
"\"\"\"Dispatches update function based on values of \n parameters.\n\n **This is purely a scalar function due to random_hypergeom**\n\n :param z: current $z$\n :param x: current $x$\n :param p: $p$ current probability\n :param xs: $x^\\star$ new state\n :param ps: $p_star$ new probability\n... | [
{
"param": "z",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "p",
"type": null
},
{
"param": "xs",
"type": null
},
{
"param": "ps",
"type": null
},
{
"param": "seed",
"type": null
},
{
"param": "validate_args",
"type": nul... | {
"returns": [
{
"docstring": "an updated number of events",
"docstring_tokens": [
"an",
"updated",
"number",
"of",
"events"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "z",
"type": null,
"docstring"... |
cb6f03639c24f69c22aac2322832b25331839bca | alefarias-dev/google-images-scrapper | scrapper.py | [
"Unlicense"
] | Python | download_images | null | def download_images(self, image_src_list):
"""
============================================
get a list of images and use urlretrieve to
try download every image in hte list
============================================
"""
repo_name = self.class_name
... |
============================================
get a list of images and use urlretrieve to
try download every image in hte list
============================================
| get a list of images and use urlretrieve to
try download every image in hte list | [
"get",
"a",
"list",
"of",
"images",
"and",
"use",
"urlretrieve",
"to",
"try",
"download",
"every",
"image",
"in",
"hte",
"list"
] | def download_images(self, image_src_list):
repo_name = self.class_name
try:
os.mkdir(repo_name)
except:
repo_name = self.class_name+'-'+str(time.time())
os.mkdir(repo_name)
images_downloaded = 0
for index, image_src in enumerate(image_src_list)... | [
"def",
"download_images",
"(",
"self",
",",
"image_src_list",
")",
":",
"repo_name",
"=",
"self",
".",
"class_name",
"try",
":",
"os",
".",
"mkdir",
"(",
"repo_name",
")",
"except",
":",
"repo_name",
"=",
"self",
".",
"class_name",
"+",
"'-'",
"+",
"str"... | get a list of images and use urlretrieve to
try download every image in hte list | [
"get",
"a",
"list",
"of",
"images",
"and",
"use",
"urlretrieve",
"to",
"try",
"download",
"every",
"image",
"in",
"hte",
"list"
] | [
"\"\"\"\n ============================================\n get a list of images and use urlretrieve to\n try download every image in hte list\n ============================================\n \"\"\"",
"# print('download [OK]: %s...' % image_src[:self.max_string_size])"
] | [
{
"param": "self",
"type": null
},
{
"param": "image_src_list",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "image_src_list",
"type": null,
"docstring": null,
"docstring_... |
cb6f03639c24f69c22aac2322832b25331839bca | alefarias-dev/google-images-scrapper | scrapper.py | [
"Unlicense"
] | Python | run | null | def run(self):
"""
============================================
receive a class name that will be used for
search images using google images tool
============================================
"""
url = "https://www.google.com.br/search?q="+self.class_name+... |
============================================
receive a class name that will be used for
search images using google images tool
============================================
| receive a class name that will be used for
search images using google images tool | [
"receive",
"a",
"class",
"name",
"that",
"will",
"be",
"used",
"for",
"search",
"images",
"using",
"google",
"images",
"tool"
] | def run(self):
url = "https://www.google.com.br/search?q="+self.class_name+"&prmd=inv&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj3mdzbnrXZAhWQuFMKHY7DAbYQ_AUIESgB#imgrc=_"
path_webdriver = "C:\\webdrivers\\chromedriver.exe"
driver = webdriver.Chrome(path_webdriver)
driver.get(url)
pri... | [
"def",
"run",
"(",
"self",
")",
":",
"url",
"=",
"\"https://www.google.com.br/search?q=\"",
"+",
"self",
".",
"class_name",
"+",
"\"&prmd=inv&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj3mdzbnrXZAhWQuFMKHY7DAbYQ_AUIESgB#imgrc=_\"",
"path_webdriver",
"=",
"\"C:\\\\webdrivers\\\\chromedriv... | receive a class name that will be used for
search images using google images tool | [
"receive",
"a",
"class",
"name",
"that",
"will",
"be",
"used",
"for",
"search",
"images",
"using",
"google",
"images",
"tool"
] | [
"\"\"\"\n ============================================\n receive a class name that will be used for\n search images using google images tool\n ============================================\n \"\"\"",
"# IMPORTANT!: the scrolls are necessary to render more images on the screen for... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0ebcf9cf9a4bdea5b0be1f42e3418dfd2a9cc0ae | cnrpman/epickitchen-on-youcook2 | youcook2/vid2img.py | [
"Apache-2.0"
] | Python | class_process | null | def class_process(dir_path, dst_dir_path, class_name=None):
"""
class_name: if specific, use specific dir for each class for src / dst; else, don't create such specific dir
"""
print('*' * 20, class_name, '*'*20)
if class_name is not None:
dir_path = os.path.join(dir_path, class_name)
... |
class_name: if specific, use specific dir for each class for src / dst; else, don't create such specific dir
| if specific, use specific dir for each class for src / dst; else, don't create such specific dir | [
"if",
"specific",
"use",
"specific",
"dir",
"for",
"each",
"class",
"for",
"src",
"/",
"dst",
";",
"else",
"don",
"'",
"t",
"create",
"such",
"specific",
"dir"
] | def class_process(dir_path, dst_dir_path, class_name=None):
print('*' * 20, class_name, '*'*20)
if class_name is not None:
dir_path = os.path.join(dir_path, class_name)
dst_dir_path = os.path.join(dst_dir_path, class_name)
if not os.path.exists(dst_dir_path):
os.mkdir(dst_dir_path)
... | [
"def",
"class_process",
"(",
"dir_path",
",",
"dst_dir_path",
",",
"class_name",
"=",
"None",
")",
":",
"print",
"(",
"'*'",
"*",
"20",
",",
"class_name",
",",
"'*'",
"*",
"20",
")",
"if",
"class_name",
"is",
"not",
"None",
":",
"dir_path",
"=",
"os",
... | class_name: if specific, use specific dir for each class for src / dst; else, don't create such specific dir | [
"class_name",
":",
"if",
"specific",
"use",
"specific",
"dir",
"for",
"each",
"class",
"for",
"src",
"/",
"dst",
";",
"else",
"don",
"'",
"t",
"create",
"such",
"specific",
"dir"
] | [
"\"\"\"\n class_name: if specific, use specific dir for each class for src / dst; else, don't create such specific dir\n \"\"\"",
"# p.map(worker, vid_list)"
] | [
{
"param": "dir_path",
"type": null
},
{
"param": "dst_dir_path",
"type": null
},
{
"param": "class_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dir_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dst_dir_path",
"type": null,
"docstring": null,
"docstrin... |
49e292fc3db8bc5f65b504f1d26e868914e87030 | tiagoad/wth2017 | themachine/workers/github/fetch_repos.py | [
"MIT"
] | Python | fetch_repo | null | def fetch_repo(data):
"""
Fetches a repository from github into a temporary directory and stores the
path into its 'local_path' parameter.
:param data: Dictionary with a repository ID as the 'id' key
"""
repo = Repository.objects.get(**data)
# create a temporary directory
tmp_dir = ... |
Fetches a repository from github into a temporary directory and stores the
path into its 'local_path' parameter.
:param data: Dictionary with a repository ID as the 'id' key
| Fetches a repository from github into a temporary directory and stores the
path into its 'local_path' parameter. | [
"Fetches",
"a",
"repository",
"from",
"github",
"into",
"a",
"temporary",
"directory",
"and",
"stores",
"the",
"path",
"into",
"its",
"'",
"local_path",
"'",
"parameter",
"."
] | def fetch_repo(data):
repo = Repository.objects.get(**data)
tmp_dir = util.tmp_dir('github')
log.info("Fetching repo %s to %s", repo.full_name, tmp_dir)
git.Repo.clone_from(repo.git_url, tmp_dir)
repo.local_path = tmp_dir
repo.save()
publish('github.repo_available', data) | [
"def",
"fetch_repo",
"(",
"data",
")",
":",
"repo",
"=",
"Repository",
".",
"objects",
".",
"get",
"(",
"**",
"data",
")",
"tmp_dir",
"=",
"util",
".",
"tmp_dir",
"(",
"'github'",
")",
"log",
".",
"info",
"(",
"\"Fetching repo %s to %s\"",
",",
"repo",
... | Fetches a repository from github into a temporary directory and stores the
path into its 'local_path' parameter. | [
"Fetches",
"a",
"repository",
"from",
"github",
"into",
"a",
"temporary",
"directory",
"and",
"stores",
"the",
"path",
"into",
"its",
"'",
"local_path",
"'",
"parameter",
"."
] | [
"\"\"\"\n Fetches a repository from github into a temporary directory and stores the\n path into its 'local_path' parameter.\n\n :param data: Dictionary with a repository ID as the 'id' key\n \"\"\"",
"# create a temporary directory",
"# log",
"# clone the repository to the directory",
"# add... | [
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": "Dictionary with a repository ID as the 'id' key",
"docstring_tokens": [
"Dictionary",
"with",
"a",
"repository",
"ID",
"as",
"the",
... |
9c449f8219d0b1856f971cbec639f2b29f1d3452 | tiagoad/wth2017 | bin/add_user.py | [
"MIT"
] | Python | main | null | def main():
"""
DEVELOPMENT SCRIPT
Starts processing the github username given as the first argument
(Publishes the username into the `github.start_user_process` topic.
"""
publish('github.start_user_process', {
'username': sys.argv[1]
}) |
DEVELOPMENT SCRIPT
Starts processing the github username given as the first argument
(Publishes the username into the `github.start_user_process` topic.
| DEVELOPMENT SCRIPT
Starts processing the github username given as the first argument
(Publishes the username into the `github.start_user_process` topic. | [
"DEVELOPMENT",
"SCRIPT",
"Starts",
"processing",
"the",
"github",
"username",
"given",
"as",
"the",
"first",
"argument",
"(",
"Publishes",
"the",
"username",
"into",
"the",
"`",
"github",
".",
"start_user_process",
"`",
"topic",
"."
] | def main():
publish('github.start_user_process', {
'username': sys.argv[1]
}) | [
"def",
"main",
"(",
")",
":",
"publish",
"(",
"'github.start_user_process'",
",",
"{",
"'username'",
":",
"sys",
".",
"argv",
"[",
"1",
"]",
"}",
")"
] | DEVELOPMENT SCRIPT
Starts processing the github username given as the first argument
(Publishes the username into the `github.start_user_process` topic. | [
"DEVELOPMENT",
"SCRIPT",
"Starts",
"processing",
"the",
"github",
"username",
"given",
"as",
"the",
"first",
"argument",
"(",
"Publishes",
"the",
"username",
"into",
"the",
"`",
"github",
".",
"start_user_process",
"`",
"topic",
"."
] | [
"\"\"\"\n DEVELOPMENT SCRIPT\n Starts processing the github username given as the first argument\n (Publishes the username into the `github.start_user_process` topic.\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
e49f6e59850c6e68e80bfd880c8540ed555194a8 | tiagoad/wth2017 | themachine/workers/github/fetch_metadata.py | [
"MIT"
] | Python | fetch_metadata | null | def fetch_metadata(data):
"""
Fetches metadata from a GitHub repository
:param data: Dictionary with a github username as the 'username' key
"""
log.info('Fetching metadata for GitHub user %s', data['username'])
gh = github.Github(os.getenv('GITHUB_TOKEN'))
gh_user = gh.get_user(data['u... |
Fetches metadata from a GitHub repository
:param data: Dictionary with a github username as the 'username' key
| Fetches metadata from a GitHub repository | [
"Fetches",
"metadata",
"from",
"a",
"GitHub",
"repository"
] | def fetch_metadata(data):
log.info('Fetching metadata for GitHub user %s', data['username'])
gh = github.Github(os.getenv('GITHUB_TOKEN'))
gh_user = gh.get_user(data['username'])
user = get_or_create(User, username=data['username'])
user.username = data['username']
user.name = gh_user.name
u... | [
"def",
"fetch_metadata",
"(",
"data",
")",
":",
"log",
".",
"info",
"(",
"'Fetching metadata for GitHub user %s'",
",",
"data",
"[",
"'username'",
"]",
")",
"gh",
"=",
"github",
".",
"Github",
"(",
"os",
".",
"getenv",
"(",
"'GITHUB_TOKEN'",
")",
")",
"gh_... | Fetches metadata from a GitHub repository | [
"Fetches",
"metadata",
"from",
"a",
"GitHub",
"repository"
] | [
"\"\"\"\n Fetches metadata from a GitHub repository\n\n :param data: Dictionary with a github username as the 'username' key\n \"\"\""
] | [
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": "Dictionary with a github username as the 'username' key",
"docstring_tokens": [
"Dictionary",
"with",
"a",
"github",
"username",
"as",
... |
2e30efebdaa5133feddc0d20155af1417d6d189c | tiagoad/wth2017 | themachine/log/__init__.py | [
"MIT"
] | Python | __log | null | def __log(level, message, *args):
"""
Logs a message into the logs.<level> topic
:param level: Log level. Should be one of the constants defined in this module
:param message: Log message
:param args: Message formatting items
"""
frame, filename, line_number, function_name, lines, inde... |
Logs a message into the logs.<level> topic
:param level: Log level. Should be one of the constants defined in this module
:param message: Log message
:param args: Message formatting items
| Logs a message into the logs. topic | [
"Logs",
"a",
"message",
"into",
"the",
"logs",
".",
"topic"
] | def __log(level, message, *args):
frame, filename, line_number, function_name, lines, index = inspect.getouterframes(inspect.currentframe())[2]
module = inspect.getmodule(frame)
publish('logs.%s' % level, {
'filename': filename,
'funcName': function_name,
'levelname': logging.getLeve... | [
"def",
"__log",
"(",
"level",
",",
"message",
",",
"*",
"args",
")",
":",
"frame",
",",
"filename",
",",
"line_number",
",",
"function_name",
",",
"lines",
",",
"index",
"=",
"inspect",
".",
"getouterframes",
"(",
"inspect",
".",
"currentframe",
"(",
")"... | Logs a message into the logs.<level> topic | [
"Logs",
"a",
"message",
"into",
"the",
"logs",
".",
"<level",
">",
"topic"
] | [
"\"\"\"\n Logs a message into the logs.<level> topic\n\n :param level: Log level. Should be one of the constants defined in this module\n :param message: Log message\n :param args: Message formatting items\n \"\"\""
] | [
{
"param": "level",
"type": null
},
{
"param": "message",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "level",
"type": null,
"docstring": "Log level. Should be one of the constants defined in this module",
"docstring_tokens": [
"Log",
"level",
".",
"Should",
"be",
"one",
"... |
2ce499b05c6a4e6ff1d5899f9875461cbf3f5250 | tiagoad/wth2017 | bin/run_api.py | [
"MIT"
] | Python | main | null | def main():
"""
DEVELOPMENT FUNCTION
Runs the API server on port 9999
"""
parser = argparse.ArgumentParser()
parser.add_argument("config", help="ini file with environment variables")
args = parser.parse_args()
# load config
config = configparser.ConfigParser()
config.optionxfo... |
DEVELOPMENT FUNCTION
Runs the API server on port 9999
| DEVELOPMENT FUNCTION
Runs the API server on port 9999 | [
"DEVELOPMENT",
"FUNCTION",
"Runs",
"the",
"API",
"server",
"on",
"port",
"9999"
] | def main():
parser = argparse.ArgumentParser()
parser.add_argument("config", help="ini file with environment variables")
args = parser.parse_args()
config = configparser.ConfigParser()
config.optionxform = str
config.read(args.config)
for key, value in config['GLOBAL'].items():
os.en... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"config\"",
",",
"help",
"=",
"\"ini file with environment variables\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
... | DEVELOPMENT FUNCTION
Runs the API server on port 9999 | [
"DEVELOPMENT",
"FUNCTION",
"Runs",
"the",
"API",
"server",
"on",
"port",
"9999"
] | [
"\"\"\"\n DEVELOPMENT FUNCTION\n\n Runs the API server on port 9999\n \"\"\"",
"# load config",
"# run api"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
9f6adae95295f4840f6a9e9f3911d917c81e6b8a | tiagoad/wth2017 | themachine/core/__init__.py | [
"MIT"
] | Python | consumer | <not_specific> | def consumer(topic, name=None):
"""
Consumer decorator.
Registers a handler with a topic, and a queue name.
Once a message is published into the topic it will be redirected to every
bound queue and processed once by one of the workers subscribed to it.
:param topic: Main topic
:param name... |
Consumer decorator.
Registers a handler with a topic, and a queue name.
Once a message is published into the topic it will be redirected to every
bound queue and processed once by one of the workers subscribed to it.
:param topic: Main topic
:param name: Queue name
:return: Di... | Consumer decorator.
Registers a handler with a topic, and a queue name.
Once a message is published into the topic it will be redirected to every
bound queue and processed once by one of the workers subscribed to it. | [
"Consumer",
"decorator",
".",
"Registers",
"a",
"handler",
"with",
"a",
"topic",
"and",
"a",
"queue",
"name",
".",
"Once",
"a",
"message",
"is",
"published",
"into",
"the",
"topic",
"it",
"will",
"be",
"redirected",
"to",
"every",
"bound",
"queue",
"and",
... | def consumer(topic, name=None):
def decorator(function):
def wrapper(ch, method, properties, body):
function(json.loads(body))
result = channel.queue_declare(
queue=name.lower() if name else '',
exclusive=True if not name else False)
channel.queue_bind(
... | [
"def",
"consumer",
"(",
"topic",
",",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"ch",
",",
"method",
",",
"properties",
",",
"body",
")",
":",
"function",
"(",
"json",
".",
"loads",
"(",
"b... | Consumer decorator. | [
"Consumer",
"decorator",
"."
] | [
"\"\"\"\n Consumer decorator.\n Registers a handler with a topic, and a queue name.\n Once a message is published into the topic it will be redirected to every\n bound queue and processed once by one of the workers subscribed to it.\n\n :param topic: Main topic\n :param name: Queue name\n\n ... | [
{
"param": "topic",
"type": null
},
{
"param": "name",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "topic",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
... |
9f6adae95295f4840f6a9e9f3911d917c81e6b8a | tiagoad/wth2017 | themachine/core/__init__.py | [
"MIT"
] | Python | publish | null | def publish(topic, data):
"""
Publishes a message into a topic.
Data should be a dictionary
:param topic: Topic to publish
:param data: Data to send
"""
channel.basic_publish(
exchange='amq.topic',
routing_key=topic.lower(),
body=json.dumps(data)) |
Publishes a message into a topic.
Data should be a dictionary
:param topic: Topic to publish
:param data: Data to send
| Publishes a message into a topic.
Data should be a dictionary | [
"Publishes",
"a",
"message",
"into",
"a",
"topic",
".",
"Data",
"should",
"be",
"a",
"dictionary"
] | def publish(topic, data):
channel.basic_publish(
exchange='amq.topic',
routing_key=topic.lower(),
body=json.dumps(data)) | [
"def",
"publish",
"(",
"topic",
",",
"data",
")",
":",
"channel",
".",
"basic_publish",
"(",
"exchange",
"=",
"'amq.topic'",
",",
"routing_key",
"=",
"topic",
".",
"lower",
"(",
")",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")"
] | Publishes a message into a topic. | [
"Publishes",
"a",
"message",
"into",
"a",
"topic",
"."
] | [
"\"\"\"\n Publishes a message into a topic.\n Data should be a dictionary\n\n :param topic: Topic to publish\n :param data: Data to send\n \"\"\""
] | [
{
"param": "topic",
"type": null
},
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "topic",
"type": null,
"docstring": "Topic to publish",
"docstring_tokens": [
"Topic",
"to",
"publish"
],
"default": null,
"is_optional": null
},
{
"identifier": "data",
... |
3cdeac1bea0c00d7f2f8cc828ba491b17ba49cb8 | tiagoad/wth2017 | themachine/workers/analysis/bandit.py | [
"MIT"
] | Python | bandit | <not_specific> | def bandit(data):
"""
Openstack Bandit consumer.
Processes a repository and inserts the report in the respository database document.
:param data: Dictionary with a repository id key
"""
repo = Repository.objects.get(**data)
# only supports Python
# TODO: use header exchange on rabbi... |
Openstack Bandit consumer.
Processes a repository and inserts the report in the respository database document.
:param data: Dictionary with a repository id key
| Openstack Bandit consumer.
Processes a repository and inserts the report in the respository database document. | [
"Openstack",
"Bandit",
"consumer",
".",
"Processes",
"a",
"repository",
"and",
"inserts",
"the",
"report",
"in",
"the",
"respository",
"database",
"document",
"."
] | def bandit(data):
repo = Repository.objects.get(**data)
if repo.language != 'Python':
return
log.info("Analysing repo %s", repo.full_name)
p = util.exec(['bandit', '-r', repo.local_path, '-f', 'json'])
result = json.loads(p.stdout)
report = BanditReport()
report.severity_high = resul... | [
"def",
"bandit",
"(",
"data",
")",
":",
"repo",
"=",
"Repository",
".",
"objects",
".",
"get",
"(",
"**",
"data",
")",
"if",
"repo",
".",
"language",
"!=",
"'Python'",
":",
"return",
"log",
".",
"info",
"(",
"\"Analysing repo %s\"",
",",
"repo",
".",
... | Openstack Bandit consumer. | [
"Openstack",
"Bandit",
"consumer",
"."
] | [
"\"\"\"\n Openstack Bandit consumer.\n Processes a repository and inserts the report in the respository database document.\n\n :param data: Dictionary with a repository id key\n \"\"\"",
"# only supports Python",
"# TODO: use header exchange on rabbitmq for filtering",
"# run bandit",
"# get ... | [
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": "Dictionary with a repository id key",
"docstring_tokens": [
"Dictionary",
"with",
"a",
"repository",
"id",
"key"
],
"default": null... |
45d53a2c8585405db27bc619fafb16e2e503dce4 | tiagoad/wth2017 | themachine/workers/log/print_logs.py | [
"MIT"
] | Python | print_log | null | def print_log(data):
"""
Log consumer.
Prints every log line into the standard output.
:param data: Log message, see themachine.log for more information
"""
print(FORMAT_STRING.format_map(data)) |
Log consumer.
Prints every log line into the standard output.
:param data: Log message, see themachine.log for more information
| Log consumer.
Prints every log line into the standard output. | [
"Log",
"consumer",
".",
"Prints",
"every",
"log",
"line",
"into",
"the",
"standard",
"output",
"."
] | def print_log(data):
print(FORMAT_STRING.format_map(data)) | [
"def",
"print_log",
"(",
"data",
")",
":",
"print",
"(",
"FORMAT_STRING",
".",
"format_map",
"(",
"data",
")",
")"
] | Log consumer. | [
"Log",
"consumer",
"."
] | [
"\"\"\"\n Log consumer.\n Prints every log line into the standard output.\n\n :param data: Log message, see themachine.log for more information\n \"\"\""
] | [
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": "Log message, see themachine.log for more information",
"docstring_tokens": [
"Log",
"message",
"see",
"themachine",
".",
"log",
"for",
... |
4f342ba809cdbdda6a90e606880c18b7ec251361 | tiagoad/wth2017 | bin/run_workers.py | [
"MIT"
] | Python | main | null | def main():
"""
DEVELOPMENT FUNCTION
Runs a list of workers on the same thread.
The workers are passed as a command line argument.
See `python run_workers.py --help` for usage information.
"""
parser = argparse.ArgumentParser()
parser.add_argument("config", help="ini file with environm... |
DEVELOPMENT FUNCTION
Runs a list of workers on the same thread.
The workers are passed as a command line argument.
See `python run_workers.py --help` for usage information.
| DEVELOPMENT FUNCTION
Runs a list of workers on the same thread.
The workers are passed as a command line argument.
See `python run_workers.py --help` for usage information. | [
"DEVELOPMENT",
"FUNCTION",
"Runs",
"a",
"list",
"of",
"workers",
"on",
"the",
"same",
"thread",
".",
"The",
"workers",
"are",
"passed",
"as",
"a",
"command",
"line",
"argument",
".",
"See",
"`",
"python",
"run_workers",
".",
"py",
"--",
"help",
"`",
"for... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("config", help="ini file with environment variables")
parser.add_argument('workers', nargs='*', help='worker names')
args = parser.parse_args()
config = configparser.ConfigParser()
config.optionxform = str
config.read(args.co... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"config\"",
",",
"help",
"=",
"\"ini file with environment variables\"",
")",
"parser",
".",
"add_argument",
"(",
"'workers'",
",",
... | DEVELOPMENT FUNCTION
Runs a list of workers on the same thread. | [
"DEVELOPMENT",
"FUNCTION",
"Runs",
"a",
"list",
"of",
"workers",
"on",
"the",
"same",
"thread",
"."
] | [
"\"\"\"\n DEVELOPMENT FUNCTION\n\n Runs a list of workers on the same thread.\n The workers are passed as a command line argument.\n See `python run_workers.py --help` for usage information.\n \"\"\"",
"# load config"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
617f6a1ecbf76c950f54c379da08d80e0299617c | blagojce95/ai-research-mamo-framework | validator.py | [
"Apache-2.0"
] | Python | evaluate | <not_specific> | def evaluate(self, disable_anneal=False, verbose=False):
"""A method that runs the validation of the model on the dataset.
Evaluate the performance of the model on the passed dataset using the
metrics and objectives in the Validator object.
Args:
verbose: A bool value deter... | A method that runs the validation of the model on the dataset.
Evaluate the performance of the model on the passed dataset using the
metrics and objectives in the Validator object.
Args:
verbose: A bool value determining whether we print to stdout.
default = True.
... | A method that runs the validation of the model on the dataset.
Evaluate the performance of the model on the passed dataset using the
metrics and objectives in the Validator object. | [
"A",
"method",
"that",
"runs",
"the",
"validation",
"of",
"the",
"model",
"on",
"the",
"dataset",
".",
"Evaluate",
"the",
"performance",
"of",
"the",
"model",
"on",
"the",
"passed",
"dataset",
"using",
"the",
"metrics",
"and",
"objectives",
"in",
"the",
"V... | def evaluate(self, disable_anneal=False, verbose=False):
if not isinstance(disable_anneal, bool):
raise TypeError('Argument: disable_anneal must be a bool.')
if not isinstance(verbose, bool):
raise TypeError('Argument: verbose must be a bool.')
device = torch.device('cuda... | [
"def",
"evaluate",
"(",
"self",
",",
"disable_anneal",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"disable_anneal",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"'Argument: disable_anneal must be a bool.'",
")",
... | A method that runs the validation of the model on the dataset. | [
"A",
"method",
"that",
"runs",
"the",
"validation",
"of",
"the",
"model",
"on",
"the",
"dataset",
"."
] | [
"\"\"\"A method that runs the validation of the model on the dataset.\n\n Evaluate the performance of the model on the passed dataset using the\n metrics and objectives in the Validator object.\n\n Args:\n verbose: A bool value determining whether we print to stdout.\n ... | [
{
"param": "self",
"type": null
},
{
"param": "disable_anneal",
"type": null
},
{
"param": "verbose",
"type": null
}
] | {
"returns": [
{
"docstring": "A tuple consiting of a list of results of the metric evaluation and\na list of results of the objective evaluation",
"docstring_tokens": [
"A",
"tuple",
"consiting",
"of",
"a",
"list",
"of",
"results",
... |
617f6a1ecbf76c950f54c379da08d80e0299617c | blagojce95/ai-research-mamo-framework | validator.py | [
"Apache-2.0"
] | Python | combine_objectives | <not_specific> | def combine_objectives(self, obj_results, alphas=None,
max_normalization=None):
"""A method combines the values passed to it.
Combine the results of objectives/losses passed using alphas and
max normalization, if set. Used after validation by the Trainer.
Exam... | A method combines the values passed to it.
Combine the results of objectives/losses passed using alphas and
max normalization, if set. Used after validation by the Trainer.
Example:
results = validator.evaluate()
validation_loss = validator.combine_objectives(results[1],... | A method combines the values passed to it.
Combine the results of objectives/losses passed using alphas and
max normalization, if set. Used after validation by the Trainer.
A list of floats.
alphas: A list of alpha values to be multiplied with the
objectives, default = None
max_normalization: A list of values to divid... | [
"A",
"method",
"combines",
"the",
"values",
"passed",
"to",
"it",
".",
"Combine",
"the",
"results",
"of",
"objectives",
"/",
"losses",
"passed",
"using",
"alphas",
"and",
"max",
"normalization",
"if",
"set",
".",
"Used",
"after",
"validation",
"by",
"the",
... | def combine_objectives(self, obj_results, alphas=None,
max_normalization=None):
if obj_results is None:
raise TypeError('Argument: obj_results must be set.')
if not isinstance(obj_results, list):
raise TypeError('Argument: obj_results must be a list.')
... | [
"def",
"combine_objectives",
"(",
"self",
",",
"obj_results",
",",
"alphas",
"=",
"None",
",",
"max_normalization",
"=",
"None",
")",
":",
"if",
"obj_results",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Argument: obj_results must be set.'",
")",
"if",
"not"... | A method combines the values passed to it. | [
"A",
"method",
"combines",
"the",
"values",
"passed",
"to",
"it",
"."
] | [
"\"\"\"A method combines the values passed to it.\n\n Combine the results of objectives/losses passed using alphas and\n max normalization, if set. Used after validation by the Trainer.\n Example:\n results = validator.evaluate()\n validation_loss = validator.combine_objec... | [
{
"param": "self",
"type": null
},
{
"param": "obj_results",
"type": null
},
{
"param": "alphas",
"type": null
},
{
"param": "max_normalization",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "obj_results",
"type": null,
"docstring": null,
"docstring_tok... |
9764b92d0cd6223ec2d68bf208596423d0ef872a | chauedwin/mf-algorithms | src/mf_algorithms/mf.py | [
"MIT"
] | Python | weightsample | <not_specific> | def weightsample(self, F, mode, **kwargs):
'''
computes the probability vector for a matrix mode for weighted sampling
Parameters:
---------------
F: matrix from which we want to weight sample
mode: either 1 or 0 (1 representing row and 0 representin... |
computes the probability vector for a matrix mode for weighted sampling
Parameters:
---------------
F: matrix from which we want to weight sample
mode: either 1 or 0 (1 representing row and 0 representing column)
| computes the probability vector for a matrix mode for weighted sampling
Parameters.
matrix from which we want to weight sample
mode: either 1 or 0 (1 representing row and 0 representing column) | [
"computes",
"the",
"probability",
"vector",
"for",
"a",
"matrix",
"mode",
"for",
"weighted",
"sampling",
"Parameters",
".",
"matrix",
"from",
"which",
"we",
"want",
"to",
"weight",
"sample",
"mode",
":",
"either",
"1",
"or",
"0",
"(",
"1",
"representing",
... | def weightsample(self, F, mode, **kwargs):
prob = np.linalg.norm(F, axis = mode)
return (prob / np.sum(prob)) | [
"def",
"weightsample",
"(",
"self",
",",
"F",
",",
"mode",
",",
"**",
"kwargs",
")",
":",
"prob",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"F",
",",
"axis",
"=",
"mode",
")",
"return",
"(",
"prob",
"/",
"np",
".",
"sum",
"(",
"prob",
")",
... | computes the probability vector for a matrix mode for weighted sampling
Parameters: | [
"computes",
"the",
"probability",
"vector",
"for",
"a",
"matrix",
"mode",
"for",
"weighted",
"sampling",
"Parameters",
":"
] | [
"'''\n computes the probability vector for a matrix mode for weighted sampling\n \n Parameters:\n ---------------\n F: matrix from which we want to weight sample \n mode: either 1 or 0 (1 representing row and 0 representing column)\n '''"
] | [
{
"param": "self",
"type": null
},
{
"param": "F",
"type": null
},
{
"param": "mode",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "F",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9764b92d0cd6223ec2d68bf208596423d0ef872a | chauedwin/mf-algorithms | src/mf_algorithms/mf.py | [
"MIT"
] | Python | leftals | <not_specific> | def leftals(self, X, lf, rf, row, **kwargs):
'''
Least squares update step
Parameters:
---------------
X: array
The data matrix "X" to be factored
lf: array
The left factor matrix to be updated
rf: array
... |
Least squares update step
Parameters:
---------------
X: array
The data matrix "X" to be factored
lf: array
The left factor matrix to be updated
rf: array
The right factor matrix used in the update
... | Least squares update step
Parameters.
array
The data matrix "X" to be factored
lf: array
The left factor matrix to be updated
rf: array
The right factor matrix used in the update
row: int
The row of the data matrix "X" used in the update | [
"Least",
"squares",
"update",
"step",
"Parameters",
".",
"array",
"The",
"data",
"matrix",
"\"",
"X",
"\"",
"to",
"be",
"factored",
"lf",
":",
"array",
"The",
"left",
"factor",
"matrix",
"to",
"be",
"updated",
"rf",
":",
"array",
"The",
"right",
"factor"... | def leftals(self, X, lf, rf, row, **kwargs):
siter = kwargs.get('siter', 1)
for i in np.arange(siter):
lf[row, :] = np.linalg.lstsq(rf.T, X[row, :].T, rcond = None)[0].T
return lf | [
"def",
"leftals",
"(",
"self",
",",
"X",
",",
"lf",
",",
"rf",
",",
"row",
",",
"**",
"kwargs",
")",
":",
"siter",
"=",
"kwargs",
".",
"get",
"(",
"'siter'",
",",
"1",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"siter",
")",
":",
"lf",
... | Least squares update step
Parameters: | [
"Least",
"squares",
"update",
"step",
"Parameters",
":"
] | [
"'''\n Least squares update step \n \n Parameters:\n ---------------\n X: array\n The data matrix \"X\" to be factored\n lf: array\n The left factor matrix to be updated\n rf: array\n The right factor matrix u... | [
{
"param": "self",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "lf",
"type": null
},
{
"param": "rf",
"type": null
},
{
"param": "row",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "X",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9764b92d0cd6223ec2d68bf208596423d0ef872a | chauedwin/mf-algorithms | src/mf_algorithms/mf.py | [
"MIT"
] | Python | leftbrk | <not_specific> | def leftbrk(self, X, lf, rf, row, **kwargs):
'''
Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters:
---------------
X: array
The data matrix "X" to be factored
... |
Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters:
---------------
X: array
The data matrix "X" to be factored
lf: array
The left factor matrix to b... | Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters.
array
The data matrix "X" to be factored
lf: array
The left factor matrix to be updated
rf: array
The right factor matrix used in the update
row: int
The row of the data matrix... | [
"Block",
"randomized",
"Kaczmarz",
"update",
"step",
"(",
"the",
"subset",
"of",
"columns",
"in",
"the",
"right",
"factor",
"matrix",
"are",
"chosen",
"via",
"weighted",
"sample",
")",
"Parameters",
".",
"array",
"The",
"data",
"matrix",
"\"",
"X",
"\"",
"... | def leftbrk(self, X, lf, rf, row, **kwargs):
siter = kwargs.get('siter', 1)
eps = kwargs.get('eps', 1e-3)
s = kwargs.get('s', 1)
for i in np.arange(siter):
if s == 1:
kaczcol = np.random.choice(rf.shape[1], size = s, p = self.weightsample(rf, 0), replace = Fal... | [
"def",
"leftbrk",
"(",
"self",
",",
"X",
",",
"lf",
",",
"rf",
",",
"row",
",",
"**",
"kwargs",
")",
":",
"siter",
"=",
"kwargs",
".",
"get",
"(",
"'siter'",
",",
"1",
")",
"eps",
"=",
"kwargs",
".",
"get",
"(",
"'eps'",
",",
"1e-3",
")",
"s"... | Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters: | [
"Block",
"randomized",
"Kaczmarz",
"update",
"step",
"(",
"the",
"subset",
"of",
"columns",
"in",
"the",
"right",
"factor",
"matrix",
"are",
"chosen",
"via",
"weighted",
"sample",
")",
"Parameters",
":"
] | [
"'''\n Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are chosen via weighted sample)\n \n Parameters:\n ---------------\n X: array\n The data matrix \"X\" to be factored\n lf: array\n The left ... | [
{
"param": "self",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "lf",
"type": null
},
{
"param": "rf",
"type": null
},
{
"param": "row",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "X",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9764b92d0cd6223ec2d68bf208596423d0ef872a | chauedwin/mf-algorithms | src/mf_algorithms/mf.py | [
"MIT"
] | Python | leftubrk | <not_specific> | def leftubrk(self, X, lf, rf, row, **kwargs):
'''
Uniform Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are uniformly sampled)
Parameters:
---------------
X: array
The data matrix "X" to be factored
... |
Uniform Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are uniformly sampled)
Parameters:
---------------
X: array
The data matrix "X" to be factored
lf: array
The left factor matrix to be... | Uniform Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are uniformly sampled)
Parameters.
array
The data matrix "X" to be factored
lf: array
The left factor matrix to be updated
rf: array
The right factor matrix used in the update
row: int
The row of the data matrix ... | [
"Uniform",
"Block",
"randomized",
"Kaczmarz",
"update",
"step",
"(",
"the",
"subset",
"of",
"columns",
"in",
"the",
"right",
"factor",
"matrix",
"are",
"uniformly",
"sampled",
")",
"Parameters",
".",
"array",
"The",
"data",
"matrix",
"\"",
"X",
"\"",
"to",
... | def leftubrk(self, X, lf, rf, row, **kwargs):
siter = kwargs.get('siter', 1)
eps = kwargs.get('eps', 1e-3)
s = kwargs.get('s', 1)
for i in np.arange(siter):
kaczcol = np.random.choice(rf.shape[1], size = s, replace = False)
if s == 1:
lf[row, :] = ... | [
"def",
"leftubrk",
"(",
"self",
",",
"X",
",",
"lf",
",",
"rf",
",",
"row",
",",
"**",
"kwargs",
")",
":",
"siter",
"=",
"kwargs",
".",
"get",
"(",
"'siter'",
",",
"1",
")",
"eps",
"=",
"kwargs",
".",
"get",
"(",
"'eps'",
",",
"1e-3",
")",
"s... | Uniform Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are uniformly sampled)
Parameters: | [
"Uniform",
"Block",
"randomized",
"Kaczmarz",
"update",
"step",
"(",
"the",
"subset",
"of",
"columns",
"in",
"the",
"right",
"factor",
"matrix",
"are",
"uniformly",
"sampled",
")",
"Parameters",
":"
] | [
"'''\n Uniform Block randomized Kaczmarz update step (the subset of columns in the right factor matrix are uniformly sampled)\n \n Parameters:\n ---------------\n X: array\n The data matrix \"X\" to be factored\n lf: array\n The left f... | [
{
"param": "self",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "lf",
"type": null
},
{
"param": "rf",
"type": null
},
{
"param": "row",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "X",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9764b92d0cd6223ec2d68bf208596423d0ef872a | chauedwin/mf-algorithms | src/mf_algorithms/mf.py | [
"MIT"
] | Python | leftbgs | <not_specific> | def leftbgs(self, X, lf, rf, row, **kwargs):
'''
Block Gauss-Seidel update rule (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters:
---------------
X: array
The data matrix "X" to be factored
lf:... |
Block Gauss-Seidel update rule (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters:
---------------
X: array
The data matrix "X" to be factored
lf: array
The left factor matrix to be updat... | Block Gauss-Seidel update rule (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters.
array
The data matrix "X" to be factored
lf: array
The left factor matrix to be updated
rf: array
The right factor matrix used in the update
row: int
The row of the data matrix "X" us... | [
"Block",
"Gauss",
"-",
"Seidel",
"update",
"rule",
"(",
"the",
"subset",
"of",
"columns",
"in",
"the",
"right",
"factor",
"matrix",
"are",
"chosen",
"via",
"weighted",
"sample",
")",
"Parameters",
".",
"array",
"The",
"data",
"matrix",
"\"",
"X",
"\"",
"... | def leftbgs(self, X, lf, rf, row, **kwargs):
siter = kwargs.get('siter', 1)
eps = kwargs.get('eps', 1e-3)
s = kwargs.get('s', 1)
k = lf.shape[1]
for j in np.arange(siter):
if s2 == 1:
gsrow = np.random.choice(rf.shape[0], size = s, p = self.weightsampl... | [
"def",
"leftbgs",
"(",
"self",
",",
"X",
",",
"lf",
",",
"rf",
",",
"row",
",",
"**",
"kwargs",
")",
":",
"siter",
"=",
"kwargs",
".",
"get",
"(",
"'siter'",
",",
"1",
")",
"eps",
"=",
"kwargs",
".",
"get",
"(",
"'eps'",
",",
"1e-3",
")",
"s"... | Block Gauss-Seidel update rule (the subset of columns in the right factor matrix are chosen via weighted sample)
Parameters: | [
"Block",
"Gauss",
"-",
"Seidel",
"update",
"rule",
"(",
"the",
"subset",
"of",
"columns",
"in",
"the",
"right",
"factor",
"matrix",
"are",
"chosen",
"via",
"weighted",
"sample",
")",
"Parameters",
":"
] | [
"'''\n Block Gauss-Seidel update rule (the subset of columns in the right factor matrix are chosen via weighted sample)\n \n Parameters:\n ---------------\n X: array\n The data matrix \"X\" to be factored\n lf: array\n The left factor ... | [
{
"param": "self",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "lf",
"type": null
},
{
"param": "rf",
"type": null
},
{
"param": "row",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "X",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
24680a376b3722ef724cf72bdc5d05bd2336a503 | leereilly/django-1 | django/views/generic/dates.py | [
"BSD-3-Clause"
] | Python | _get_dated_items | <not_specific> | def _get_dated_items(self, date):
"""
Do the actual heavy lifting of getting the dated items; this accepts a
date object so that TodayArchiveView can be trivial.
"""
date_field = self.get_date_field()
field = self.get_queryset().model._meta.get_field(date_field)
... |
Do the actual heavy lifting of getting the dated items; this accepts a
date object so that TodayArchiveView can be trivial.
| Do the actual heavy lifting of getting the dated items; this accepts a
date object so that TodayArchiveView can be trivial. | [
"Do",
"the",
"actual",
"heavy",
"lifting",
"of",
"getting",
"the",
"dated",
"items",
";",
"this",
"accepts",
"a",
"date",
"object",
"so",
"that",
"TodayArchiveView",
"can",
"be",
"trivial",
"."
] | def _get_dated_items(self, date):
date_field = self.get_date_field()
field = self.get_queryset().model._meta.get_field(date_field)
lookup_kwargs = _date_lookup_for_field(field, date)
qs = self.get_dated_queryset(**lookup_kwargs)
return (None, qs, {
'day': date,
... | [
"def",
"_get_dated_items",
"(",
"self",
",",
"date",
")",
":",
"date_field",
"=",
"self",
".",
"get_date_field",
"(",
")",
"field",
"=",
"self",
".",
"get_queryset",
"(",
")",
".",
"model",
".",
"_meta",
".",
"get_field",
"(",
"date_field",
")",
"lookup_... | Do the actual heavy lifting of getting the dated items; this accepts a
date object so that TodayArchiveView can be trivial. | [
"Do",
"the",
"actual",
"heavy",
"lifting",
"of",
"getting",
"the",
"dated",
"items",
";",
"this",
"accepts",
"a",
"date",
"object",
"so",
"that",
"TodayArchiveView",
"can",
"be",
"trivial",
"."
] | [
"\"\"\"\n Do the actual heavy lifting of getting the dated items; this accepts a\n date object so that TodayArchiveView can be trivial.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "date",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "date",
"type": null,
"docstring": null,
"docstring_tokens": [... |
24680a376b3722ef724cf72bdc5d05bd2336a503 | leereilly/django-1 | django/views/generic/dates.py | [
"BSD-3-Clause"
] | Python | _date_from_string | <not_specific> | def _date_from_string(year, year_format, month, month_format, day='', day_format='', delim='__'):
"""
Helper: get a datetime.date object given a format string and a year,
month, and possibly day; raise a 404 for an invalid date.
"""
format = delim.join((year_format, month_format, day_format))
da... |
Helper: get a datetime.date object given a format string and a year,
month, and possibly day; raise a 404 for an invalid date.
| get a datetime.date object given a format string and a year,
month, and possibly day; raise a 404 for an invalid date. | [
"get",
"a",
"datetime",
".",
"date",
"object",
"given",
"a",
"format",
"string",
"and",
"a",
"year",
"month",
"and",
"possibly",
"day",
";",
"raise",
"a",
"404",
"for",
"an",
"invalid",
"date",
"."
] | def _date_from_string(year, year_format, month, month_format, day='', day_format='', delim='__'):
format = delim.join((year_format, month_format, day_format))
datestr = delim.join((year, month, day))
try:
return datetime.datetime.strptime(datestr, format).date()
except ValueError:
raise ... | [
"def",
"_date_from_string",
"(",
"year",
",",
"year_format",
",",
"month",
",",
"month_format",
",",
"day",
"=",
"''",
",",
"day_format",
"=",
"''",
",",
"delim",
"=",
"'__'",
")",
":",
"format",
"=",
"delim",
".",
"join",
"(",
"(",
"year_format",
",",... | Helper: get a datetime.date object given a format string and a year,
month, and possibly day; raise a 404 for an invalid date. | [
"Helper",
":",
"get",
"a",
"datetime",
".",
"date",
"object",
"given",
"a",
"format",
"string",
"and",
"a",
"year",
"month",
"and",
"possibly",
"day",
";",
"raise",
"a",
"404",
"for",
"an",
"invalid",
"date",
"."
] | [
"\"\"\"\n Helper: get a datetime.date object given a format string and a year,\n month, and possibly day; raise a 404 for an invalid date.\n \"\"\""
] | [
{
"param": "year",
"type": null
},
{
"param": "year_format",
"type": null
},
{
"param": "month",
"type": null
},
{
"param": "month_format",
"type": null
},
{
"param": "day",
"type": null
},
{
"param": "day_format",
"type": null
},
{
"param"... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "year",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "year_format",
"type": null,
"docstring": null,
"docstring_tok... |
24680a376b3722ef724cf72bdc5d05bd2336a503 | leereilly/django-1 | django/views/generic/dates.py | [
"BSD-3-Clause"
] | Python | _get_next_prev_month | <not_specific> | def _get_next_prev_month(generic_view, naive_result, is_previous, use_first_day):
"""
Helper: Get the next or the previous valid date. The idea is to allow
links on month/day views to never be 404s by never providing a date
that'll be invalid for the given view.
This is a bit complicated since it h... |
Helper: Get the next or the previous valid date. The idea is to allow
links on month/day views to never be 404s by never providing a date
that'll be invalid for the given view.
This is a bit complicated since it handles both next and previous months
and days (for MonthArchiveView and DayArchiveVie... | Get the next or the previous valid date. The idea is to allow
links on month/day views to never be 404s by never providing a date
that'll be invalid for the given view.
This is a bit complicated since it handles both next and previous months
and days (for MonthArchiveView and DayArchiveView); hence the coupling to gen... | [
"Get",
"the",
"next",
"or",
"the",
"previous",
"valid",
"date",
".",
"The",
"idea",
"is",
"to",
"allow",
"links",
"on",
"month",
"/",
"day",
"views",
"to",
"never",
"be",
"404s",
"by",
"never",
"providing",
"a",
"date",
"that",
"'",
"ll",
"be",
"inva... | def _get_next_prev_month(generic_view, naive_result, is_previous, use_first_day):
date_field = generic_view.get_date_field()
allow_empty = generic_view.get_allow_empty()
allow_future = generic_view.get_allow_future()
if allow_empty:
result = naive_result
else:
if is_previous:
... | [
"def",
"_get_next_prev_month",
"(",
"generic_view",
",",
"naive_result",
",",
"is_previous",
",",
"use_first_day",
")",
":",
"date_field",
"=",
"generic_view",
".",
"get_date_field",
"(",
")",
"allow_empty",
"=",
"generic_view",
".",
"get_allow_empty",
"(",
")",
"... | Helper: Get the next or the previous valid date. | [
"Helper",
":",
"Get",
"the",
"next",
"or",
"the",
"previous",
"valid",
"date",
"."
] | [
"\"\"\"\n Helper: Get the next or the previous valid date. The idea is to allow\n links on month/day views to never be 404s by never providing a date\n that'll be invalid for the given view.\n\n This is a bit complicated since it handles both next and previous months\n and days (for MonthArchiveView ... | [
{
"param": "generic_view",
"type": null
},
{
"param": "naive_result",
"type": null
},
{
"param": "is_previous",
"type": null
},
{
"param": "use_first_day",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "generic_view",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "naive_result",
"type": null,
"docstring": null,
"docs... |
24680a376b3722ef724cf72bdc5d05bd2336a503 | leereilly/django-1 | django/views/generic/dates.py | [
"BSD-3-Clause"
] | Python | _date_lookup_for_field | <not_specific> | def _date_lookup_for_field(field, date):
"""
Get the lookup kwargs for looking up a date against a given Field. If the
date field is a DateTimeField, we can't just do filter(df=date) because
that doesn't take the time into account. So we need to make a range lookup
in those cases.
"""
if isi... |
Get the lookup kwargs for looking up a date against a given Field. If the
date field is a DateTimeField, we can't just do filter(df=date) because
that doesn't take the time into account. So we need to make a range lookup
in those cases.
| Get the lookup kwargs for looking up a date against a given Field. If the
date field is a DateTimeField, we can't just do filter(df=date) because
that doesn't take the time into account. So we need to make a range lookup
in those cases. | [
"Get",
"the",
"lookup",
"kwargs",
"for",
"looking",
"up",
"a",
"date",
"against",
"a",
"given",
"Field",
".",
"If",
"the",
"date",
"field",
"is",
"a",
"DateTimeField",
"we",
"can",
"'",
"t",
"just",
"do",
"filter",
"(",
"df",
"=",
"date",
")",
"becau... | def _date_lookup_for_field(field, date):
if isinstance(field, models.DateTimeField):
date_range = (
datetime.datetime.combine(date, datetime.time.min),
datetime.datetime.combine(date, datetime.time.max)
)
return {'%s__range' % field.name: date_range}
else:
... | [
"def",
"_date_lookup_for_field",
"(",
"field",
",",
"date",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"models",
".",
"DateTimeField",
")",
":",
"date_range",
"=",
"(",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"date",
",",
"datetime",
".",
... | Get the lookup kwargs for looking up a date against a given Field. | [
"Get",
"the",
"lookup",
"kwargs",
"for",
"looking",
"up",
"a",
"date",
"against",
"a",
"given",
"Field",
"."
] | [
"\"\"\"\n Get the lookup kwargs for looking up a date against a given Field. If the\n date field is a DateTimeField, we can't just do filter(df=date) because\n that doesn't take the time into account. So we need to make a range lookup\n in those cases.\n \"\"\""
] | [
{
"param": "field",
"type": null
},
{
"param": "date",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "field",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "date",
"type": null,
"docstring": null,
"docstring_tokens": ... |
981e8339299c8258e07001e068ce1fbd54ad1ddb | kareef928/hyppo | hyppo/independence/hhg.py | [
"MIT"
] | Python | _pearson_stat | <not_specific> | def _pearson_stat(distx, disty): # pragma: no cover
"""Calculate the Pearson chi square stats"""
n = distx.shape[0]
S = np.zeros((n, n))
# iterate over all samples in the distance matrix
for i in range(n):
for j in range(n):
if i != j:
a = distx[i, :] <= distx[... | Calculate the Pearson chi square stats | Calculate the Pearson chi square stats | [
"Calculate",
"the",
"Pearson",
"chi",
"square",
"stats"
] | def _pearson_stat(distx, disty):
n = distx.shape[0]
S = np.zeros((n, n))
for i in range(n):
for j in range(n):
if i != j:
a = distx[i, :] <= distx[i, j]
b = disty[i, :] <= disty[i, j]
t11 = np.sum(a * b) - 2
t12 = np.sum(a... | [
"def",
"_pearson_stat",
"(",
"distx",
",",
"disty",
")",
":",
"n",
"=",
"distx",
".",
"shape",
"[",
"0",
"]",
"S",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"for",
"j",
"in",
... | Calculate the Pearson chi square stats | [
"Calculate",
"the",
"Pearson",
"chi",
"square",
"stats"
] | [
"# pragma: no cover",
"\"\"\"Calculate the Pearson chi square stats\"\"\"",
"# iterate over all samples in the distance matrix"
] | [
{
"param": "distx",
"type": null
},
{
"param": "disty",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "distx",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "disty",
"type": null,
"docstring": null,
"docstring_tokens":... |
15f0f8d78836044d305d039543b4baaac2954e59 | kareef928/hyppo | hyppo/discrim/_utils.py | [
"MIT"
] | Python | _condition_input | <not_specific> | def _condition_input(self, x1):
"""Checks whether there is only one subject and removes
isolates and calculate distance."""
uniques, counts = np.unique(self.y, return_counts=True)
if (counts != 1).sum() <= 1:
msg = "You have passed a vector containing only a single unique sa... | Checks whether there is only one subject and removes
isolates and calculate distance. | Checks whether there is only one subject and removes
isolates and calculate distance. | [
"Checks",
"whether",
"there",
"is",
"only",
"one",
"subject",
"and",
"removes",
"isolates",
"and",
"calculate",
"distance",
"."
] | def _condition_input(self, x1):
uniques, counts = np.unique(self.y, return_counts=True)
if (counts != 1).sum() <= 1:
msg = "You have passed a vector containing only a single unique sample id."
raise ValueError(msg)
if self.remove_isolates:
idx = np.isin(self.y... | [
"def",
"_condition_input",
"(",
"self",
",",
"x1",
")",
":",
"uniques",
",",
"counts",
"=",
"np",
".",
"unique",
"(",
"self",
".",
"y",
",",
"return_counts",
"=",
"True",
")",
"if",
"(",
"counts",
"!=",
"1",
")",
".",
"sum",
"(",
")",
"<=",
"1",
... | Checks whether there is only one subject and removes
isolates and calculate distance. | [
"Checks",
"whether",
"there",
"is",
"only",
"one",
"subject",
"and",
"removes",
"isolates",
"and",
"calculate",
"distance",
"."
] | [
"\"\"\"Checks whether there is only one subject and removes\n isolates and calculate distance.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "x1",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x1",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
15f0f8d78836044d305d039543b4baaac2954e59 | kareef928/hyppo | hyppo/discrim/_utils.py | [
"MIT"
] | Python | check_min_samples | null | def check_min_samples(x1):
"""Check if the number of samples is at least 3"""
nx = x1.shape[0]
if nx <= 10:
raise ValueError("Number of samples is too low") | Check if the number of samples is at least 3 | Check if the number of samples is at least 3 | [
"Check",
"if",
"the",
"number",
"of",
"samples",
"is",
"at",
"least",
"3"
] | def check_min_samples(x1):
nx = x1.shape[0]
if nx <= 10:
raise ValueError("Number of samples is too low") | [
"def",
"check_min_samples",
"(",
"x1",
")",
":",
"nx",
"=",
"x1",
".",
"shape",
"[",
"0",
"]",
"if",
"nx",
"<=",
"10",
":",
"raise",
"ValueError",
"(",
"\"Number of samples is too low\"",
")"
] | Check if the number of samples is at least 3 | [
"Check",
"if",
"the",
"number",
"of",
"samples",
"is",
"at",
"least",
"3"
] | [
"\"\"\"Check if the number of samples is at least 3\"\"\""
] | [
{
"param": "x1",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x1",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
896f5a85019a815ec33b4d580639be656593536c | kareef928/hyppo | hyppo/time_series/_utils.py | [
"MIT"
] | Python | compute_scale_at_lag | <not_specific> | def compute_scale_at_lag(x, y, opt_lag, compute_distance, **kwargs):
"""Run the mgc test at the optimal scale (by shifting the series)."""
n = x.shape[0]
if not compute_distance:
compute_distance = "precomputed"
distx, disty = compute_dist(x, y, metric=compute_distance, **kwargs)
slice_dist... | Run the mgc test at the optimal scale (by shifting the series). | Run the mgc test at the optimal scale (by shifting the series). | [
"Run",
"the",
"mgc",
"test",
"at",
"the",
"optimal",
"scale",
"(",
"by",
"shifting",
"the",
"series",
")",
"."
] | def compute_scale_at_lag(x, y, opt_lag, compute_distance, **kwargs):
n = x.shape[0]
if not compute_distance:
compute_distance = "precomputed"
distx, disty = compute_dist(x, y, metric=compute_distance, **kwargs)
slice_distx = distx[opt_lag:n, opt_lag:n]
slice_disty = disty[0 : (n - opt_lag), ... | [
"def",
"compute_scale_at_lag",
"(",
"x",
",",
"y",
",",
"opt_lag",
",",
"compute_distance",
",",
"**",
"kwargs",
")",
":",
"n",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"if",
"not",
"compute_distance",
":",
"compute_distance",
"=",
"\"precomputed\"",
"distx"... | Run the mgc test at the optimal scale (by shifting the series). | [
"Run",
"the",
"mgc",
"test",
"at",
"the",
"optimal",
"scale",
"(",
"by",
"shifting",
"the",
"series",
")",
"."
] | [
"\"\"\"Run the mgc test at the optimal scale (by shifting the series).\"\"\""
] | [
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "opt_lag",
"type": null
},
{
"param": "compute_distance",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
dd6e1bfd9a0bb2156489c957a9981498bd0e44f9 | kareef928/hyppo | hyppo/independence/_utils.py | [
"MIT"
] | Python | check_dim_xy | <not_specific> | def check_dim_xy(self):
"""Convert x and y to proper dimensions"""
if self.x.ndim == 1:
self.x = self.x[:, np.newaxis]
elif self.x.ndim != 2:
raise ValueError(
"Expected a 2-D array `x`, found shape " "{}".format(self.x.shape)
)
if self... | Convert x and y to proper dimensions | Convert x and y to proper dimensions | [
"Convert",
"x",
"and",
"y",
"to",
"proper",
"dimensions"
] | def check_dim_xy(self):
if self.x.ndim == 1:
self.x = self.x[:, np.newaxis]
elif self.x.ndim != 2:
raise ValueError(
"Expected a 2-D array `x`, found shape " "{}".format(self.x.shape)
)
if self.y.ndim == 1:
self.y = self.y[:, np.new... | [
"def",
"check_dim_xy",
"(",
"self",
")",
":",
"if",
"self",
".",
"x",
".",
"ndim",
"==",
"1",
":",
"self",
".",
"x",
"=",
"self",
".",
"x",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"elif",
"self",
".",
"x",
".",
"ndim",
"!=",
"2",
":",
"ra... | Convert x and y to proper dimensions | [
"Convert",
"x",
"and",
"y",
"to",
"proper",
"dimensions"
] | [
"\"\"\"Convert x and y to proper dimensions\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
dd6e1bfd9a0bb2156489c957a9981498bd0e44f9 | kareef928/hyppo | hyppo/independence/_utils.py | [
"MIT"
] | Python | _check_nd_indeptest | null | def _check_nd_indeptest(self):
"""Check if number of samples is the same"""
nx, _ = self.x.shape
ny, _ = self.y.shape
if nx != ny:
raise ValueError(
"Shape mismatch, x and y must have shape " "[n, p] and [n, q]."
) | Check if number of samples is the same | Check if number of samples is the same | [
"Check",
"if",
"number",
"of",
"samples",
"is",
"the",
"same"
] | def _check_nd_indeptest(self):
nx, _ = self.x.shape
ny, _ = self.y.shape
if nx != ny:
raise ValueError(
"Shape mismatch, x and y must have shape " "[n, p] and [n, q]."
) | [
"def",
"_check_nd_indeptest",
"(",
"self",
")",
":",
"nx",
",",
"_",
"=",
"self",
".",
"x",
".",
"shape",
"ny",
",",
"_",
"=",
"self",
".",
"y",
".",
"shape",
"if",
"nx",
"!=",
"ny",
":",
"raise",
"ValueError",
"(",
"\"Shape mismatch, x and y must have... | Check if number of samples is the same | [
"Check",
"if",
"number",
"of",
"samples",
"is",
"the",
"same"
] | [
"\"\"\"Check if number of samples is the same\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
dd6e1bfd9a0bb2156489c957a9981498bd0e44f9 | kareef928/hyppo | hyppo/independence/_utils.py | [
"MIT"
] | Python | _check_min_samples | null | def _check_min_samples(self):
"""Check if the number of samples is at least 3"""
nx = self.x.shape[0]
ny = self.y.shape[0]
if nx <= 3 or ny <= 3:
raise ValueError("Number of samples is too low") | Check if the number of samples is at least 3 | Check if the number of samples is at least 3 | [
"Check",
"if",
"the",
"number",
"of",
"samples",
"is",
"at",
"least",
"3"
] | def _check_min_samples(self):
nx = self.x.shape[0]
ny = self.y.shape[0]
if nx <= 3 or ny <= 3:
raise ValueError("Number of samples is too low") | [
"def",
"_check_min_samples",
"(",
"self",
")",
":",
"nx",
"=",
"self",
".",
"x",
".",
"shape",
"[",
"0",
"]",
"ny",
"=",
"self",
".",
"y",
".",
"shape",
"[",
"0",
"]",
"if",
"nx",
"<=",
"3",
"or",
"ny",
"<=",
"3",
":",
"raise",
"ValueError",
... | Check if the number of samples is at least 3 | [
"Check",
"if",
"the",
"number",
"of",
"samples",
"is",
"at",
"least",
"3"
] | [
"\"\"\"Check if the number of samples is at least 3\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
dd6e1bfd9a0bb2156489c957a9981498bd0e44f9 | kareef928/hyppo | hyppo/independence/_utils.py | [
"MIT"
] | Python | sim_matrix | <not_specific> | def sim_matrix(model, x):
"""
Computes the similarity matrix from a random forest.
The model used must follow the scikit-learn API. That is, the model is a random
forest class and is already trained (use :func:`fit`) before running this function.
Also, :func:`apply` must be used to push input data ... |
Computes the similarity matrix from a random forest.
The model used must follow the scikit-learn API. That is, the model is a random
forest class and is already trained (use :func:`fit`) before running this function.
Also, :func:`apply` must be used to push input data down the trained forest. See
... | Computes the similarity matrix from a random forest.
The model used must follow the scikit-learn API. That is, the model is a random
forest class and is already trained (use :func:`fit`) before running this function.
Also, :func:`apply` must be used to push input data down the trained forest. See | [
"Computes",
"the",
"similarity",
"matrix",
"from",
"a",
"random",
"forest",
".",
"The",
"model",
"used",
"must",
"follow",
"the",
"scikit",
"-",
"learn",
"API",
".",
"That",
"is",
"the",
"model",
"is",
"a",
"random",
"forest",
"class",
"and",
"is",
"alre... | def sim_matrix(model, x):
terminals = model.apply(x)
ntrees = terminals.shape[1]
prox_mat = sum(
np.equal.outer(terminals[:, i], terminals[:, i]) for i in range(ntrees)
)
prox_mat = prox_mat / ntrees
return prox_mat | [
"def",
"sim_matrix",
"(",
"model",
",",
"x",
")",
":",
"terminals",
"=",
"model",
".",
"apply",
"(",
"x",
")",
"ntrees",
"=",
"terminals",
".",
"shape",
"[",
"1",
"]",
"prox_mat",
"=",
"sum",
"(",
"np",
".",
"equal",
".",
"outer",
"(",
"terminals",... | Computes the similarity matrix from a random forest. | [
"Computes",
"the",
"similarity",
"matrix",
"from",
"a",
"random",
"forest",
"."
] | [
"\"\"\"\n Computes the similarity matrix from a random forest.\n\n The model used must follow the scikit-learn API. That is, the model is a random\n forest class and is already trained (use :func:`fit`) before running this function.\n Also, :func:`apply` must be used to push input data down the trained ... | [
{
"param": "model",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
b2de4acd15b30b4048358672040511f20dbf3569 | kareef928/hyppo | examples/feat_import.py | [
"MIT"
] | Python | tree_import | <not_specific> | def tree_import(sim_name):
"""Train a random forest for a given simulation, calculate feature importance."""
# simulate data
x, y = SIMULATIONS[sim_name](SIM_SIZE, DIM)
if y.shape[1] == 1:
y = y.ravel()
with warnings.catch_warnings():
# get feature importances
_, _, importan... | Train a random forest for a given simulation, calculate feature importance. | Train a random forest for a given simulation, calculate feature importance. | [
"Train",
"a",
"random",
"forest",
"for",
"a",
"given",
"simulation",
"calculate",
"feature",
"importance",
"."
] | def tree_import(sim_name):
x, y = SIMULATIONS[sim_name](SIM_SIZE, DIM)
if y.shape[1] == 1:
y = y.ravel()
with warnings.catch_warnings():
_, _, importances = KMERF(forest="regressor", ntrees=FOREST_SIZE).test(
x, y, reps=0
)
return importances | [
"def",
"tree_import",
"(",
"sim_name",
")",
":",
"x",
",",
"y",
"=",
"SIMULATIONS",
"[",
"sim_name",
"]",
"(",
"SIM_SIZE",
",",
"DIM",
")",
"if",
"y",
".",
"shape",
"[",
"1",
"]",
"==",
"1",
":",
"y",
"=",
"y",
".",
"ravel",
"(",
")",
"with",
... | Train a random forest for a given simulation, calculate feature importance. | [
"Train",
"a",
"random",
"forest",
"for",
"a",
"given",
"simulation",
"calculate",
"feature",
"importance",
"."
] | [
"\"\"\"Train a random forest for a given simulation, calculate feature importance.\"\"\"",
"# simulate data",
"# get feature importances"
] | [
{
"param": "sim_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "sim_name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b2de4acd15b30b4048358672040511f20dbf3569 | kareef928/hyppo | examples/feat_import.py | [
"MIT"
] | Python | estimate_featimport | <not_specific> | def estimate_featimport(sim_name, rep):
"""Run this function to calculate the feature importances"""
est_featimpt = tree_import(sim_name)
np.savetxt(
"../examples/data/{}_{}.csv".format(sim_name, rep), est_featimpt, delimiter=","
)
return est_featimpt | Run this function to calculate the feature importances | Run this function to calculate the feature importances | [
"Run",
"this",
"function",
"to",
"calculate",
"the",
"feature",
"importances"
] | def estimate_featimport(sim_name, rep):
est_featimpt = tree_import(sim_name)
np.savetxt(
"../examples/data/{}_{}.csv".format(sim_name, rep), est_featimpt, delimiter=","
)
return est_featimpt | [
"def",
"estimate_featimport",
"(",
"sim_name",
",",
"rep",
")",
":",
"est_featimpt",
"=",
"tree_import",
"(",
"sim_name",
")",
"np",
".",
"savetxt",
"(",
"\"../examples/data/{}_{}.csv\"",
".",
"format",
"(",
"sim_name",
",",
"rep",
")",
",",
"est_featimpt",
",... | Run this function to calculate the feature importances | [
"Run",
"this",
"function",
"to",
"calculate",
"the",
"feature",
"importances"
] | [
"\"\"\"Run this function to calculate the feature importances\"\"\""
] | [
{
"param": "sim_name",
"type": null
},
{
"param": "rep",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "sim_name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "rep",
"type": null,
"docstring": null,
"docstring_tokens"... |
b2de4acd15b30b4048358672040511f20dbf3569 | kareef928/hyppo | examples/feat_import.py | [
"MIT"
] | Python | plot_featimport_confint | null | def plot_featimport_confint():
"""Plot feature importances and 95% confidence intervals"""
fig, ax = plt.subplots(nrows=4, ncols=5, figsize=(25, 20))
plt.suptitle("Feature Importances", y=0.93, va="baseline")
for i, row in enumerate(ax):
for j, col in enumerate(row):
# get the pan... | Plot feature importances and 95% confidence intervals | Plot feature importances and 95% confidence intervals | [
"Plot",
"feature",
"importances",
"and",
"95%",
"confidence",
"intervals"
] | def plot_featimport_confint():
fig, ax = plt.subplots(nrows=4, ncols=5, figsize=(25, 20))
plt.suptitle("Feature Importances", y=0.93, va="baseline")
for i, row in enumerate(ax):
for j, col in enumerate(row):
count = 5 * i + j
sim_name = list(SIMULATIONS.keys())[count]
... | [
"def",
"plot_featimport_confint",
"(",
")",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"4",
",",
"ncols",
"=",
"5",
",",
"figsize",
"=",
"(",
"25",
",",
"20",
")",
")",
"plt",
".",
"suptitle",
"(",
"\"Feature Importances\"... | Plot feature importances and 95% confidence intervals | [
"Plot",
"feature",
"importances",
"and",
"95%",
"confidence",
"intervals"
] | [
"\"\"\"Plot feature importances and 95% confidence intervals\"\"\"",
"# get the panel location and simulation name",
"# extract data from the CSV file and store the data in an array",
"# get the mean importances for the simulation, also calculate 95% CI",
"# interval",
"# plot the figure lines, and the 95... | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
df3e2edb101f2c623790b38f914c5924dc1996ee | kapoorlab/arboretum | arboretum/layers/tracks/qt_tracks_layer.py | [
"MIT"
] | Python | _on_edge_width_change | null | def _on_edge_width_change(self, event=None):
"""Receive layer model edge line width change event and update slider.
Parameters
----------
event : qtpy.QtCore.QEvent, optional.
Event from the Qt context, by default None.
"""
with self.layer.events.edge_width.b... | Receive layer model edge line width change event and update slider.
Parameters
----------
event : qtpy.QtCore.QEvent, optional.
Event from the Qt context, by default None.
| Receive layer model edge line width change event and update slider.
Parameters
| [
"Receive",
"layer",
"model",
"edge",
"line",
"width",
"change",
"event",
"and",
"update",
"slider",
".",
"Parameters"
] | def _on_edge_width_change(self, event=None):
with self.layer.events.edge_width.blocker():
value = self.layer.edge_width
value = np.clip(int(2 * value), 1, MAX_TAIL_WIDTH)
self.edge_width_slider.setValue(value) | [
"def",
"_on_edge_width_change",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"with",
"self",
".",
"layer",
".",
"events",
".",
"edge_width",
".",
"blocker",
"(",
")",
":",
"value",
"=",
"self",
".",
"layer",
".",
"edge_width",
"value",
"=",
"np",
... | Receive layer model edge line width change event and update slider. | [
"Receive",
"layer",
"model",
"edge",
"line",
"width",
"change",
"event",
"and",
"update",
"slider",
"."
] | [
"\"\"\"Receive layer model edge line width change event and update slider.\n\n Parameters\n ----------\n event : qtpy.QtCore.QEvent, optional.\n Event from the Qt context, by default None.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "event",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "event",
"type": null,
"docstring": null,
"docstring_tokens": ... |
df3e2edb101f2c623790b38f914c5924dc1996ee | kapoorlab/arboretum | arboretum/layers/tracks/qt_tracks_layer.py | [
"MIT"
] | Python | change_width | null | def change_width(self, value):
"""Change edge line width of shapes on the layer model.
Parameters
----------
value : float
Line width of shapes.
"""
self.layer.edge_width = float(value) / 2.0 | Change edge line width of shapes on the layer model.
Parameters
----------
value : float
Line width of shapes.
| Change edge line width of shapes on the layer model.
Parameters
value : float
Line width of shapes. | [
"Change",
"edge",
"line",
"width",
"of",
"shapes",
"on",
"the",
"layer",
"model",
".",
"Parameters",
"value",
":",
"float",
"Line",
"width",
"of",
"shapes",
"."
] | def change_width(self, value):
self.layer.edge_width = float(value) / 2.0 | [
"def",
"change_width",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"layer",
".",
"edge_width",
"=",
"float",
"(",
"value",
")",
"/",
"2.0"
] | Change edge line width of shapes on the layer model. | [
"Change",
"edge",
"line",
"width",
"of",
"shapes",
"on",
"the",
"layer",
"model",
"."
] | [
"\"\"\"Change edge line width of shapes on the layer model.\n\n Parameters\n ----------\n value : float\n Line width of shapes.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "value",
"type": null,
"docstring": null,
"docstring_tokens": ... |
df3e2edb101f2c623790b38f914c5924dc1996ee | kapoorlab/arboretum | arboretum/layers/tracks/qt_tracks_layer.py | [
"MIT"
] | Python | _on_tail_length_change | null | def _on_tail_length_change(self, event=None):
"""Receive layer model edge line width change event and update slider.
Parameters
----------
event : qtpy.QtCore.QEvent, optional.
Event from the Qt context, by default None.
"""
with self.layer.events.tail_length... | Receive layer model edge line width change event and update slider.
Parameters
----------
event : qtpy.QtCore.QEvent, optional.
Event from the Qt context, by default None.
| Receive layer model edge line width change event and update slider.
Parameters
| [
"Receive",
"layer",
"model",
"edge",
"line",
"width",
"change",
"event",
"and",
"update",
"slider",
".",
"Parameters"
] | def _on_tail_length_change(self, event=None):
with self.layer.events.tail_length.blocker():
value = self.layer.tail_length
value = np.clip(value, 1, MAX_TAIL_LENGTH)
self.tail_length_slider.setValue(value) | [
"def",
"_on_tail_length_change",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"with",
"self",
".",
"layer",
".",
"events",
".",
"tail_length",
".",
"blocker",
"(",
")",
":",
"value",
"=",
"self",
".",
"layer",
".",
"tail_length",
"value",
"=",
"np... | Receive layer model edge line width change event and update slider. | [
"Receive",
"layer",
"model",
"edge",
"line",
"width",
"change",
"event",
"and",
"update",
"slider",
"."
] | [
"\"\"\"Receive layer model edge line width change event and update slider.\n\n Parameters\n ----------\n event : qtpy.QtCore.QEvent, optional.\n Event from the Qt context, by default None.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "event",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "event",
"type": null,
"docstring": null,
"docstring_tokens": ... |
e81b9a23027e2d854bf8f2e389416ff18b4252fb | kapoorlab/arboretum | arboretum/tree.py | [
"MIT"
] | Python | _build_tree_graph | <not_specific> | def _build_tree_graph(root, nodes):
""" built the graph of the tree """
max_generational_depth = max([n.generation for n in nodes])
#put the start vertex into the queue, and the marked list
queue = [root]
marked = [root]
y_pos = [0]
# store the line coordinates that need to be plotted
... | built the graph of the tree | built the graph of the tree | [
"built",
"the",
"graph",
"of",
"the",
"tree"
] | def _build_tree_graph(root, nodes):
max_generational_depth = max([n.generation for n in nodes])
queue = [root]
marked = [root]
y_pos = [0]
edges = []
annotations = []
markers = []
while queue:
node = queue.pop(0)
y = y_pos.pop(0)
depth = float(node.generation) / m... | [
"def",
"_build_tree_graph",
"(",
"root",
",",
"nodes",
")",
":",
"max_generational_depth",
"=",
"max",
"(",
"[",
"n",
".",
"generation",
"for",
"n",
"in",
"nodes",
"]",
")",
"queue",
"=",
"[",
"root",
"]",
"marked",
"=",
"[",
"root",
"]",
"y_pos",
"=... | built the graph of the tree | [
"built",
"the",
"graph",
"of",
"the",
"tree"
] | [
"\"\"\" built the graph of the tree \"\"\"",
"#put the start vertex into the queue, and the marked list",
"# store the line coordinates that need to be plotted",
"# now step through",
"# pop the root from the tree",
"# TODO(arl): sync this with layer coloring",
"# draw the root of the tree",
"# mark i... | [
{
"param": "root",
"type": null
},
{
"param": "nodes",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "root",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "nodes",
"type": null,
"docstring": null,
"docstring_tokens": ... |
eb3444bae7322e3983bf751548545af22efa1b31 | kapoorlab/arboretum | arboretum/plugin.py | [
"MIT"
] | Python | load_data | null | def load_data(self):
""" load data in hdf or json format from btrack """
filename = QFileDialog.getOpenFileName(self,
'Open tracking data',
DEFAULT_PATH,
'Tracking... | load data in hdf or json format from btrack | load data in hdf or json format from btrack | [
"load",
"data",
"in",
"hdf",
"or",
"json",
"format",
"from",
"btrack"
] | def load_data(self):
filename = QFileDialog.getOpenFileName(self,
'Open tracking data',
DEFAULT_PATH,
'Tracking files (*.hdf5 *.h5)')
if filename[0]:
s... | [
"def",
"load_data",
"(",
"self",
")",
":",
"filename",
"=",
"QFileDialog",
".",
"getOpenFileName",
"(",
"self",
",",
"'Open tracking data'",
",",
"DEFAULT_PATH",
",",
"'Tracking files (*.hdf5 *.h5)'",
")",
"if",
"filename",
"[",
"0",
"]",
":",
"self",
".",
"fi... | load data in hdf or json format from btrack | [
"load",
"data",
"in",
"hdf",
"or",
"json",
"format",
"from",
"btrack"
] | [
"\"\"\" load data in hdf or json format from btrack \"\"\"",
"# only load file if we actually chose one"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
eb3444bae7322e3983bf751548545af22efa1b31 | kapoorlab/arboretum | arboretum/plugin.py | [
"MIT"
] | Python | volume | tuple | def volume(self) -> tuple:
""" get the volume to use for tracking """
if self.segmentation is None:
return ((0,1200), (0,1600), (-1e5,1e5))
else:
volume = []
# assumes time is the first dimension
for dim in self.segmentation.shape[-2:]:
... | get the volume to use for tracking | get the volume to use for tracking | [
"get",
"the",
"volume",
"to",
"use",
"for",
"tracking"
] | def volume(self) -> tuple:
if self.segmentation is None:
return ((0,1200), (0,1600), (-1e5,1e5))
else:
volume = []
for dim in self.segmentation.shape[-2:]:
volume.append((0, dim))
if len(volume) == 2:
volume.append((-1e5, 1e5))... | [
"def",
"volume",
"(",
"self",
")",
"->",
"tuple",
":",
"if",
"self",
".",
"segmentation",
"is",
"None",
":",
"return",
"(",
"(",
"0",
",",
"1200",
")",
",",
"(",
"0",
",",
"1600",
")",
",",
"(",
"-",
"1e5",
",",
"1e5",
")",
")",
"else",
":",
... | get the volume to use for tracking | [
"get",
"the",
"volume",
"to",
"use",
"for",
"tracking"
] | [
"\"\"\" get the volume to use for tracking \"\"\"",
"# assumes time is the first dimension",
"#",
"# if len(volume) == 2:"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0ba6adbbd9c2328315c029f643a0f2eed7bcaa2f | kapoorlab/arboretum | arboretum/layers/tracks/_track_utils.py | [
"MIT"
] | Python | check_track_dimensionality | <not_specific> | def check_track_dimensionality(data: list):
""" check the dimensionality of the data
TODO(arl): we could allow a mix of 2D/3D etc...
"""
assert all([isinstance(d, np.ndarray) for d in data])
assert all([d.shape[1] == data[0].shape[1] for d in data])
return data[0].shape[1] | check the dimensionality of the data
TODO(arl): we could allow a mix of 2D/3D etc...
| check the dimensionality of the data
TODO(arl): we could allow a mix of 2D/3D etc | [
"check",
"the",
"dimensionality",
"of",
"the",
"data",
"TODO",
"(",
"arl",
")",
":",
"we",
"could",
"allow",
"a",
"mix",
"of",
"2D",
"/",
"3D",
"etc"
] | def check_track_dimensionality(data: list):
assert all([isinstance(d, np.ndarray) for d in data])
assert all([d.shape[1] == data[0].shape[1] for d in data])
return data[0].shape[1] | [
"def",
"check_track_dimensionality",
"(",
"data",
":",
"list",
")",
":",
"assert",
"all",
"(",
"[",
"isinstance",
"(",
"d",
",",
"np",
".",
"ndarray",
")",
"for",
"d",
"in",
"data",
"]",
")",
"assert",
"all",
"(",
"[",
"d",
".",
"shape",
"[",
"1",
... | check the dimensionality of the data
TODO(arl): we could allow a mix of 2D/3D etc... | [
"check",
"the",
"dimensionality",
"of",
"the",
"data",
"TODO",
"(",
"arl",
")",
":",
"we",
"could",
"allow",
"a",
"mix",
"of",
"2D",
"/",
"3D",
"etc",
"..."
] | [
"\"\"\" check the dimensionality of the data\n\n TODO(arl): we could allow a mix of 2D/3D etc...\n \"\"\""
] | [
{
"param": "data",
"type": "list"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": "list",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0ba6adbbd9c2328315c029f643a0f2eed7bcaa2f | kapoorlab/arboretum | arboretum/layers/tracks/_track_utils.py | [
"MIT"
] | Python | data | null | def data(self, data: list):
""" set the data and build the vispy arrays for display """
self._data = data
# build the track data for vispy
self._track_vertices = np.concatenate(self.data, axis=0)
self._track_connex = np.concatenate([connex(d) for d in data], axis=0)
# b... | set the data and build the vispy arrays for display | set the data and build the vispy arrays for display | [
"set",
"the",
"data",
"and",
"build",
"the",
"vispy",
"arrays",
"for",
"display"
] | def data(self, data: list):
self._data = data
self._track_vertices = np.concatenate(self.data, axis=0)
self._track_connex = np.concatenate([connex(d) for d in data], axis=0)
self._ordered_points_idx = np.argsort(self._track_vertices[:, 0])
self._points = self._track_vertices[self... | [
"def",
"data",
"(",
"self",
",",
"data",
":",
"list",
")",
":",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_track_vertices",
"=",
"np",
".",
"concatenate",
"(",
"self",
".",
"data",
",",
"axis",
"=",
"0",
")",
"self",
".",
"_track_connex",
"=... | set the data and build the vispy arrays for display | [
"set",
"the",
"data",
"and",
"build",
"the",
"vispy",
"arrays",
"for",
"display"
] | [
"\"\"\" set the data and build the vispy arrays for display \"\"\"",
"# build the track data for vispy",
"# build the indices for sorting points by time",
"# build a tree of the track data to allow fast lookup of nearest track",
"# make the lookup table",
"# NOTE(arl): it's important to convert the time i... | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": "list"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": "list",
"docstring": null,
"docstring_tokens":... |
0ba6adbbd9c2328315c029f643a0f2eed7bcaa2f | kapoorlab/arboretum | arboretum/layers/tracks/_track_utils.py | [
"MIT"
] | Python | build_graph | <not_specific> | def build_graph(self):
""" build_graph
Build the track graph using track properties. The track graph should be:
[(track_idx, (parent_idx,...)),...]
"""
# if we don't have any properties, then return gracefully
if not self.properties:
return
if... | build_graph
Build the track graph using track properties. The track graph should be:
[(track_idx, (parent_idx,...)),...]
| build_graph
Build the track graph using track properties. The track graph should be.
| [
"build_graph",
"Build",
"the",
"track",
"graph",
"using",
"track",
"properties",
".",
"The",
"track",
"graph",
"should",
"be",
"."
] | def build_graph(self):
if not self.properties:
return
if 'parent' not in self._property_keys:
return
track_lookup = [track['ID'] for track in self.properties]
track_parents = [track['parent'] for track in self.properties]
branches = zip(track_lookup, track... | [
"def",
"build_graph",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"properties",
":",
"return",
"if",
"'parent'",
"not",
"in",
"self",
".",
"_property_keys",
":",
"return",
"track_lookup",
"=",
"[",
"track",
"[",
"'ID'",
"]",
"for",
"track",
"in",
... | build_graph
Build the track graph using track properties. | [
"build_graph",
"Build",
"the",
"track",
"graph",
"using",
"track",
"properties",
"."
] | [
"\"\"\" build_graph\n\n Build the track graph using track properties. The track graph should be:\n\n [(track_idx, (parent_idx,...)),...]\n\n \"\"\"",
"# if we don't have any properties, then return gracefully",
"# now remove any root nodes",
"# TODO(arl): parent can also be a list in ... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.