repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ggravlingen/pytradfri
pytradfri/smart_task.py
TaskControl.tasks
def tasks(self): """Return task objects of the task control.""" return [StartActionItem( self._task, i, self.state, self.path, self.raw) for i in range(len(self.raw))]
python
def tasks(self): """Return task objects of the task control.""" return [StartActionItem( self._task, i, self.state, self.path, self.raw) for i in range(len(self.raw))]
[ "def", "tasks", "(", "self", ")", ":", "return", "[", "StartActionItem", "(", "self", ".", "_task", ",", "i", ",", "self", ".", "state", ",", "self", ".", "path", ",", "self", ".", "raw", ")", "for", "i", "in", "range", "(", "len", "(", "self", ...
Return task objects of the task control.
[ "Return", "task", "objects", "of", "the", "task", "control", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/smart_task.py#L161-L168
train
206,700
ggravlingen/pytradfri
pytradfri/smart_task.py
StartActionItemController.set_dimmer
def set_dimmer(self, dimmer): """Set final dimmer value for task.""" command = { ATTR_START_ACTION: { ATTR_DEVICE_STATE: self.state, ROOT_START_ACTION: [{ ATTR_ID: self.raw[ATTR_ID], ATTR_LIGHT_DIMMER: dimmer, ATTR_TRANSITION_TIME: self.raw[ATTR_TRANSITION_TIME] }, self.devices_dict] } } return self.set_values(command)
python
def set_dimmer(self, dimmer): """Set final dimmer value for task.""" command = { ATTR_START_ACTION: { ATTR_DEVICE_STATE: self.state, ROOT_START_ACTION: [{ ATTR_ID: self.raw[ATTR_ID], ATTR_LIGHT_DIMMER: dimmer, ATTR_TRANSITION_TIME: self.raw[ATTR_TRANSITION_TIME] }, self.devices_dict] } } return self.set_values(command)
[ "def", "set_dimmer", "(", "self", ",", "dimmer", ")", ":", "command", "=", "{", "ATTR_START_ACTION", ":", "{", "ATTR_DEVICE_STATE", ":", "self", ".", "state", ",", "ROOT_START_ACTION", ":", "[", "{", "ATTR_ID", ":", "self", ".", "raw", "[", "ATTR_ID", "]...
Set final dimmer value for task.
[ "Set", "final", "dimmer", "value", "for", "task", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/smart_task.py#L299-L311
train
206,701
ggravlingen/pytradfri
pytradfri/resource.py
ApiResource.observe
def observe(self, callback, err_callback, duration=60): """Observe resource and call callback when updated.""" def observe_callback(value): """ Called when end point is updated. Returns a Command. """ self.raw = value callback(self) return Command('get', self.path, process_result=observe_callback, err_callback=err_callback, observe=True, observe_duration=duration)
python
def observe(self, callback, err_callback, duration=60): """Observe resource and call callback when updated.""" def observe_callback(value): """ Called when end point is updated. Returns a Command. """ self.raw = value callback(self) return Command('get', self.path, process_result=observe_callback, err_callback=err_callback, observe=True, observe_duration=duration)
[ "def", "observe", "(", "self", ",", "callback", ",", "err_callback", ",", "duration", "=", "60", ")", ":", "def", "observe_callback", "(", "value", ")", ":", "\"\"\"\n Called when end point is updated.\n\n Returns a Command.\n \"\"\"", "self...
Observe resource and call callback when updated.
[ "Observe", "resource", "and", "call", "callback", "when", "updated", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/resource.py#L37-L51
train
206,702
ggravlingen/pytradfri
pytradfri/resource.py
ApiResource.update
def update(self): """ Update the group. Returns a Command. """ def process_result(result): self.raw = result return Command('get', self.path, process_result=process_result)
python
def update(self): """ Update the group. Returns a Command. """ def process_result(result): self.raw = result return Command('get', self.path, process_result=process_result)
[ "def", "update", "(", "self", ")", ":", "def", "process_result", "(", "result", ")", ":", "self", ".", "raw", "=", "result", "return", "Command", "(", "'get'", ",", "self", ".", "path", ",", "process_result", "=", "process_result", ")" ]
Update the group. Returns a Command.
[ "Update", "the", "group", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/resource.py#L67-L75
train
206,703
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.generate_psk
def generate_psk(self, identity): """ Generates the PRE_SHARED_KEY from the gateway. Returns a Command. """ def process_result(result): return result[ATTR_PSK] return Command('post', [ROOT_GATEWAY, ATTR_AUTH], { ATTR_IDENTITY: identity }, process_result=process_result)
python
def generate_psk(self, identity): """ Generates the PRE_SHARED_KEY from the gateway. Returns a Command. """ def process_result(result): return result[ATTR_PSK] return Command('post', [ROOT_GATEWAY, ATTR_AUTH], { ATTR_IDENTITY: identity }, process_result=process_result)
[ "def", "generate_psk", "(", "self", ",", "identity", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "result", "[", "ATTR_PSK", "]", "return", "Command", "(", "'post'", ",", "[", "ROOT_GATEWAY", ",", "ATTR_AUTH", "]", ",", "{", "ATT...
Generates the PRE_SHARED_KEY from the gateway. Returns a Command.
[ "Generates", "the", "PRE_SHARED_KEY", "from", "the", "gateway", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L22-L33
train
206,704
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_endpoints
def get_endpoints(self): """ Return all available endpoints on the gateway. Returns a Command. """ def process_result(result): return [line.split(';')[0][2:-1] for line in result.split(',')] return Command('get', ['.well-known', 'core'], parse_json=False, process_result=process_result)
python
def get_endpoints(self): """ Return all available endpoints on the gateway. Returns a Command. """ def process_result(result): return [line.split(';')[0][2:-1] for line in result.split(',')] return Command('get', ['.well-known', 'core'], parse_json=False, process_result=process_result)
[ "def", "get_endpoints", "(", "self", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "[", "line", ".", "split", "(", "';'", ")", "[", "0", "]", "[", "2", ":", "-", "1", "]", "for", "line", "in", "result", ".", "split", "(", ...
Return all available endpoints on the gateway. Returns a Command.
[ "Return", "all", "available", "endpoints", "on", "the", "gateway", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L35-L45
train
206,705
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_devices
def get_devices(self): """ Return the devices linked to the gateway. Returns a Command. """ def process_result(result): return [self.get_device(dev) for dev in result] return Command('get', [ROOT_DEVICES], process_result=process_result)
python
def get_devices(self): """ Return the devices linked to the gateway. Returns a Command. """ def process_result(result): return [self.get_device(dev) for dev in result] return Command('get', [ROOT_DEVICES], process_result=process_result)
[ "def", "get_devices", "(", "self", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "[", "self", ".", "get_device", "(", "dev", ")", "for", "dev", "in", "result", "]", "return", "Command", "(", "'get'", ",", "[", "ROOT_DEVICES", "]...
Return the devices linked to the gateway. Returns a Command.
[ "Return", "the", "devices", "linked", "to", "the", "gateway", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L47-L56
train
206,706
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_device
def get_device(self, device_id): """ Return specified device. Returns a Command. """ def process_result(result): return Device(result) return Command('get', [ROOT_DEVICES, device_id], process_result=process_result)
python
def get_device(self, device_id): """ Return specified device. Returns a Command. """ def process_result(result): return Device(result) return Command('get', [ROOT_DEVICES, device_id], process_result=process_result)
[ "def", "get_device", "(", "self", ",", "device_id", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "Device", "(", "result", ")", "return", "Command", "(", "'get'", ",", "[", "ROOT_DEVICES", ",", "device_id", "]", ",", "process_result...
Return specified device. Returns a Command.
[ "Return", "specified", "device", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L58-L68
train
206,707
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_groups
def get_groups(self): """ Return the groups linked to the gateway. Returns a Command. """ def process_result(result): return [self.get_group(group) for group in result] return Command('get', [ROOT_GROUPS], process_result=process_result)
python
def get_groups(self): """ Return the groups linked to the gateway. Returns a Command. """ def process_result(result): return [self.get_group(group) for group in result] return Command('get', [ROOT_GROUPS], process_result=process_result)
[ "def", "get_groups", "(", "self", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "[", "self", ".", "get_group", "(", "group", ")", "for", "group", "in", "result", "]", "return", "Command", "(", "'get'", ",", "[", "ROOT_GROUPS", "...
Return the groups linked to the gateway. Returns a Command.
[ "Return", "the", "groups", "linked", "to", "the", "gateway", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L70-L79
train
206,708
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_group
def get_group(self, group_id): """ Return specified group. Returns a Command. """ def process_result(result): return Group(self, result) return Command('get', [ROOT_GROUPS, group_id], process_result=process_result)
python
def get_group(self, group_id): """ Return specified group. Returns a Command. """ def process_result(result): return Group(self, result) return Command('get', [ROOT_GROUPS, group_id], process_result=process_result)
[ "def", "get_group", "(", "self", ",", "group_id", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "Group", "(", "self", ",", "result", ")", "return", "Command", "(", "'get'", ",", "[", "ROOT_GROUPS", ",", "group_id", "]", ",", "pr...
Return specified group. Returns a Command.
[ "Return", "specified", "group", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L81-L91
train
206,709
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_gateway_info
def get_gateway_info(self): """ Return the gateway info. Returns a Command. """ def process_result(result): return GatewayInfo(result) return Command('get', [ROOT_GATEWAY, ATTR_GATEWAY_INFO], process_result=process_result)
python
def get_gateway_info(self): """ Return the gateway info. Returns a Command. """ def process_result(result): return GatewayInfo(result) return Command('get', [ROOT_GATEWAY, ATTR_GATEWAY_INFO], process_result=process_result)
[ "def", "get_gateway_info", "(", "self", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "GatewayInfo", "(", "result", ")", "return", "Command", "(", "'get'", ",", "[", "ROOT_GATEWAY", ",", "ATTR_GATEWAY_INFO", "]", ",", "process_result", ...
Return the gateway info. Returns a Command.
[ "Return", "the", "gateway", "info", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L93-L104
train
206,710
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_moods
def get_moods(self): """ Return moods defined on the gateway. Returns a Command. """ mood_parent = self._get_mood_parent() def process_result(result): return [self.get_mood(mood, mood_parent=mood_parent) for mood in result] return Command('get', [ROOT_MOODS, mood_parent], process_result=process_result)
python
def get_moods(self): """ Return moods defined on the gateway. Returns a Command. """ mood_parent = self._get_mood_parent() def process_result(result): return [self.get_mood(mood, mood_parent=mood_parent) for mood in result] return Command('get', [ROOT_MOODS, mood_parent], process_result=process_result)
[ "def", "get_moods", "(", "self", ")", ":", "mood_parent", "=", "self", ".", "_get_mood_parent", "(", ")", "def", "process_result", "(", "result", ")", ":", "return", "[", "self", ".", "get_mood", "(", "mood", ",", "mood_parent", "=", "mood_parent", ")", ...
Return moods defined on the gateway. Returns a Command.
[ "Return", "moods", "defined", "on", "the", "gateway", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L106-L119
train
206,711
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_mood
def get_mood(self, mood_id, *, mood_parent=None): """ Return a mood. Returns a Command. """ if mood_parent is None: mood_parent = self._get_mood_parent() def process_result(result): return Mood(result, mood_parent) return Command('get', [ROOT_MOODS, mood_parent, mood_id], mood_parent, process_result=process_result)
python
def get_mood(self, mood_id, *, mood_parent=None): """ Return a mood. Returns a Command. """ if mood_parent is None: mood_parent = self._get_mood_parent() def process_result(result): return Mood(result, mood_parent) return Command('get', [ROOT_MOODS, mood_parent, mood_id], mood_parent, process_result=process_result)
[ "def", "get_mood", "(", "self", ",", "mood_id", ",", "*", ",", "mood_parent", "=", "None", ")", ":", "if", "mood_parent", "is", "None", ":", "mood_parent", "=", "self", ".", "_get_mood_parent", "(", ")", "def", "process_result", "(", "result", ")", ":", ...
Return a mood. Returns a Command.
[ "Return", "a", "mood", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L121-L134
train
206,712
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_smart_tasks
def get_smart_tasks(self): """ Return the transitions linked to the gateway. Returns a Command. """ def process_result(result): return [self.get_smart_task(task) for task in result] return Command('get', [ROOT_SMART_TASKS], process_result=process_result)
python
def get_smart_tasks(self): """ Return the transitions linked to the gateway. Returns a Command. """ def process_result(result): return [self.get_smart_task(task) for task in result] return Command('get', [ROOT_SMART_TASKS], process_result=process_result)
[ "def", "get_smart_tasks", "(", "self", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "[", "self", ".", "get_smart_task", "(", "task", ")", "for", "task", "in", "result", "]", "return", "Command", "(", "'get'", ",", "[", "ROOT_SMAR...
Return the transitions linked to the gateway. Returns a Command.
[ "Return", "the", "transitions", "linked", "to", "the", "gateway", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L147-L157
train
206,713
ggravlingen/pytradfri
pytradfri/gateway.py
Gateway.get_smart_task
def get_smart_task(self, task_id): """ Return specified transition. Returns a Command. """ def process_result(result): return SmartTask(self, result) return Command('get', [ROOT_SMART_TASKS, task_id], process_result=process_result)
python
def get_smart_task(self, task_id): """ Return specified transition. Returns a Command. """ def process_result(result): return SmartTask(self, result) return Command('get', [ROOT_SMART_TASKS, task_id], process_result=process_result)
[ "def", "get_smart_task", "(", "self", ",", "task_id", ")", ":", "def", "process_result", "(", "result", ")", ":", "return", "SmartTask", "(", "self", ",", "result", ")", "return", "Command", "(", "'get'", ",", "[", "ROOT_SMART_TASKS", ",", "task_id", "]", ...
Return specified transition. Returns a Command.
[ "Return", "specified", "transition", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L159-L169
train
206,714
ggravlingen/pytradfri
pytradfri/gateway.py
GatewayInfo.first_setup
def first_setup(self): """This is a guess of the meaning of this value.""" if ATTR_FIRST_SETUP not in self.raw: return None return datetime.utcfromtimestamp(self.raw[ATTR_FIRST_SETUP])
python
def first_setup(self): """This is a guess of the meaning of this value.""" if ATTR_FIRST_SETUP not in self.raw: return None return datetime.utcfromtimestamp(self.raw[ATTR_FIRST_SETUP])
[ "def", "first_setup", "(", "self", ")", ":", "if", "ATTR_FIRST_SETUP", "not", "in", "self", ".", "raw", ":", "return", "None", "return", "datetime", ".", "utcfromtimestamp", "(", "self", ".", "raw", "[", "ATTR_FIRST_SETUP", "]", ")" ]
This is a guess of the meaning of this value.
[ "This", "is", "a", "guess", "of", "the", "meaning", "of", "this", "value", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/gateway.py#L235-L239
train
206,715
ggravlingen/pytradfri
pytradfri/device.py
DeviceInfo.power_source_str
def power_source_str(self): """String representation of current power source.""" if DeviceInfo.ATTR_POWER_SOURCE not in self.raw: return None return DeviceInfo.VALUE_POWER_SOURCES.get(self.power_source, 'Unknown')
python
def power_source_str(self): """String representation of current power source.""" if DeviceInfo.ATTR_POWER_SOURCE not in self.raw: return None return DeviceInfo.VALUE_POWER_SOURCES.get(self.power_source, 'Unknown')
[ "def", "power_source_str", "(", "self", ")", ":", "if", "DeviceInfo", ".", "ATTR_POWER_SOURCE", "not", "in", "self", ".", "raw", ":", "return", "None", "return", "DeviceInfo", ".", "VALUE_POWER_SOURCES", ".", "get", "(", "self", ".", "power_source", ",", "'U...
String representation of current power source.
[ "String", "representation", "of", "current", "power", "source", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L137-L141
train
206,716
ggravlingen/pytradfri
pytradfri/device.py
LightControl.lights
def lights(self): """Return light objects of the light control.""" return [Light(self._device, i) for i in range(len(self.raw))]
python
def lights(self): """Return light objects of the light control.""" return [Light(self._device, i) for i in range(len(self.raw))]
[ "def", "lights", "(", "self", ")", ":", "return", "[", "Light", "(", "self", ".", "_device", ",", "i", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "raw", ")", ")", "]" ]
Return light objects of the light control.
[ "Return", "light", "objects", "of", "the", "light", "control", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L200-L202
train
206,717
ggravlingen/pytradfri
pytradfri/device.py
LightControl.set_state
def set_state(self, state, *, index=0): """Set state of a light.""" return self.set_values({ ATTR_DEVICE_STATE: int(state) }, index=index)
python
def set_state(self, state, *, index=0): """Set state of a light.""" return self.set_values({ ATTR_DEVICE_STATE: int(state) }, index=index)
[ "def", "set_state", "(", "self", ",", "state", ",", "*", ",", "index", "=", "0", ")", ":", "return", "self", ".", "set_values", "(", "{", "ATTR_DEVICE_STATE", ":", "int", "(", "state", ")", "}", ",", "index", "=", "index", ")" ]
Set state of a light.
[ "Set", "state", "of", "a", "light", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L204-L208
train
206,718
ggravlingen/pytradfri
pytradfri/device.py
LightControl.set_color_temp
def set_color_temp(self, color_temp, *, index=0, transition_time=None): """Set color temp a light.""" self._value_validate(color_temp, RANGE_MIREDS, "Color temperature") values = { ATTR_LIGHT_MIREDS: color_temp } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
python
def set_color_temp(self, color_temp, *, index=0, transition_time=None): """Set color temp a light.""" self._value_validate(color_temp, RANGE_MIREDS, "Color temperature") values = { ATTR_LIGHT_MIREDS: color_temp } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
[ "def", "set_color_temp", "(", "self", ",", "color_temp", ",", "*", ",", "index", "=", "0", ",", "transition_time", "=", "None", ")", ":", "self", ".", "_value_validate", "(", "color_temp", ",", "RANGE_MIREDS", ",", "\"Color temperature\"", ")", "values", "="...
Set color temp a light.
[ "Set", "color", "temp", "a", "light", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L225-L236
train
206,719
ggravlingen/pytradfri
pytradfri/device.py
LightControl.set_hex_color
def set_hex_color(self, color, *, index=0, transition_time=None): """Set hex color of the light.""" values = { ATTR_LIGHT_COLOR_HEX: color, } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
python
def set_hex_color(self, color, *, index=0, transition_time=None): """Set hex color of the light.""" values = { ATTR_LIGHT_COLOR_HEX: color, } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
[ "def", "set_hex_color", "(", "self", ",", "color", ",", "*", ",", "index", "=", "0", ",", "transition_time", "=", "None", ")", ":", "values", "=", "{", "ATTR_LIGHT_COLOR_HEX", ":", "color", ",", "}", "if", "transition_time", "is", "not", "None", ":", "...
Set hex color of the light.
[ "Set", "hex", "color", "of", "the", "light", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L238-L247
train
206,720
ggravlingen/pytradfri
pytradfri/device.py
LightControl.set_xy_color
def set_xy_color(self, color_x, color_y, *, index=0, transition_time=None): """Set xy color of the light.""" self._value_validate(color_x, RANGE_X, "X color") self._value_validate(color_y, RANGE_Y, "Y color") values = { ATTR_LIGHT_COLOR_X: color_x, ATTR_LIGHT_COLOR_Y: color_y } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
python
def set_xy_color(self, color_x, color_y, *, index=0, transition_time=None): """Set xy color of the light.""" self._value_validate(color_x, RANGE_X, "X color") self._value_validate(color_y, RANGE_Y, "Y color") values = { ATTR_LIGHT_COLOR_X: color_x, ATTR_LIGHT_COLOR_Y: color_y } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
[ "def", "set_xy_color", "(", "self", ",", "color_x", ",", "color_y", ",", "*", ",", "index", "=", "0", ",", "transition_time", "=", "None", ")", ":", "self", ".", "_value_validate", "(", "color_x", ",", "RANGE_X", ",", "\"X color\"", ")", "self", ".", "...
Set xy color of the light.
[ "Set", "xy", "color", "of", "the", "light", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L249-L262
train
206,721
ggravlingen/pytradfri
pytradfri/device.py
LightControl.set_hsb
def set_hsb(self, hue, saturation, brightness=None, *, index=0, transition_time=None): """Set HSB color settings of the light.""" self._value_validate(hue, RANGE_HUE, "Hue") self._value_validate(saturation, RANGE_SATURATION, "Saturation") values = { ATTR_LIGHT_COLOR_SATURATION: saturation, ATTR_LIGHT_COLOR_HUE: hue } if brightness is not None: values[ATTR_LIGHT_DIMMER] = brightness self._value_validate(brightness, RANGE_BRIGHTNESS, "Brightness") if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
python
def set_hsb(self, hue, saturation, brightness=None, *, index=0, transition_time=None): """Set HSB color settings of the light.""" self._value_validate(hue, RANGE_HUE, "Hue") self._value_validate(saturation, RANGE_SATURATION, "Saturation") values = { ATTR_LIGHT_COLOR_SATURATION: saturation, ATTR_LIGHT_COLOR_HUE: hue } if brightness is not None: values[ATTR_LIGHT_DIMMER] = brightness self._value_validate(brightness, RANGE_BRIGHTNESS, "Brightness") if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
[ "def", "set_hsb", "(", "self", ",", "hue", ",", "saturation", ",", "brightness", "=", "None", ",", "*", ",", "index", "=", "0", ",", "transition_time", "=", "None", ")", ":", "self", ".", "_value_validate", "(", "hue", ",", "RANGE_HUE", ",", "\"Hue\"",...
Set HSB color settings of the light.
[ "Set", "HSB", "color", "settings", "of", "the", "light", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L264-L282
train
206,722
ggravlingen/pytradfri
pytradfri/device.py
LightControl._value_validate
def _value_validate(self, value, rnge, identifier="Given"): """ Make sure a value is within a given range """ if value is not None and (value < rnge[0] or value > rnge[1]): raise ValueError('%s value must be between %d and %d.' % (identifier, rnge[0], rnge[1]))
python
def _value_validate(self, value, rnge, identifier="Given"): """ Make sure a value is within a given range """ if value is not None and (value < rnge[0] or value > rnge[1]): raise ValueError('%s value must be between %d and %d.' % (identifier, rnge[0], rnge[1]))
[ "def", "_value_validate", "(", "self", ",", "value", ",", "rnge", ",", "identifier", "=", "\"Given\"", ")", ":", "if", "value", "is", "not", "None", "and", "(", "value", "<", "rnge", "[", "0", "]", "or", "value", ">", "rnge", "[", "1", "]", ")", ...
Make sure a value is within a given range
[ "Make", "sure", "a", "value", "is", "within", "a", "given", "range" ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L294-L300
train
206,723
ggravlingen/pytradfri
pytradfri/device.py
LightControl.set_values
def set_values(self, values, *, index=0): """ Set values on light control. Returns a Command. """ assert len(self.raw) == 1, \ 'Only devices with 1 light supported' return Command('put', self._device.path, { ATTR_LIGHT_CONTROL: [ values ] })
python
def set_values(self, values, *, index=0): """ Set values on light control. Returns a Command. """ assert len(self.raw) == 1, \ 'Only devices with 1 light supported' return Command('put', self._device.path, { ATTR_LIGHT_CONTROL: [ values ] })
[ "def", "set_values", "(", "self", ",", "values", ",", "*", ",", "index", "=", "0", ")", ":", "assert", "len", "(", "self", ".", "raw", ")", "==", "1", ",", "'Only devices with 1 light supported'", "return", "Command", "(", "'put'", ",", "self", ".", "_...
Set values on light control. Returns a Command.
[ "Set", "values", "on", "light", "control", ".", "Returns", "a", "Command", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L302-L314
train
206,724
ggravlingen/pytradfri
pytradfri/device.py
SocketControl.sockets
def sockets(self): """Return socket objects of the socket control.""" return [Socket(self._device, i) for i in range(len(self.raw))]
python
def sockets(self): """Return socket objects of the socket control.""" return [Socket(self._device, i) for i in range(len(self.raw))]
[ "def", "sockets", "(", "self", ")", ":", "return", "[", "Socket", "(", "self", ".", "_device", ",", "i", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "raw", ")", ")", "]" ]
Return socket objects of the socket control.
[ "Return", "socket", "objects", "of", "the", "socket", "control", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/device.py#L401-L403
train
206,725
ggravlingen/pytradfri
pytradfri/api/aiocoap_api.py
APIFactory._get_protocol
async def _get_protocol(self): """Get the protocol for the request.""" if self._protocol is None: self._protocol = asyncio.Task(Context.create_client_context( loop=self._loop)) return (await self._protocol)
python
async def _get_protocol(self): """Get the protocol for the request.""" if self._protocol is None: self._protocol = asyncio.Task(Context.create_client_context( loop=self._loop)) return (await self._protocol)
[ "async", "def", "_get_protocol", "(", "self", ")", ":", "if", "self", ".", "_protocol", "is", "None", ":", "self", ".", "_protocol", "=", "asyncio", ".", "Task", "(", "Context", ".", "create_client_context", "(", "loop", "=", "self", ".", "_loop", ")", ...
Get the protocol for the request.
[ "Get", "the", "protocol", "for", "the", "request", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/api/aiocoap_api.py#L67-L72
train
206,726
ggravlingen/pytradfri
pytradfri/api/aiocoap_api.py
APIFactory._reset_protocol
async def _reset_protocol(self, exc=None): """Reset the protocol if an error occurs.""" # Be responsible and clean up. protocol = await self._get_protocol() await protocol.shutdown() self._protocol = None # Let any observers know the protocol has been shutdown. for ob_error in self._observations_err_callbacks: ob_error(exc) self._observations_err_callbacks.clear()
python
async def _reset_protocol(self, exc=None): """Reset the protocol if an error occurs.""" # Be responsible and clean up. protocol = await self._get_protocol() await protocol.shutdown() self._protocol = None # Let any observers know the protocol has been shutdown. for ob_error in self._observations_err_callbacks: ob_error(exc) self._observations_err_callbacks.clear()
[ "async", "def", "_reset_protocol", "(", "self", ",", "exc", "=", "None", ")", ":", "# Be responsible and clean up.", "protocol", "=", "await", "self", ".", "_get_protocol", "(", ")", "await", "protocol", ".", "shutdown", "(", ")", "self", ".", "_protocol", "...
Reset the protocol if an error occurs.
[ "Reset", "the", "protocol", "if", "an", "error", "occurs", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/api/aiocoap_api.py#L74-L83
train
206,727
ggravlingen/pytradfri
pytradfri/api/aiocoap_api.py
APIFactory._get_response
async def _get_response(self, msg): """Perform the request, get the response.""" try: protocol = await self._get_protocol() pr = protocol.request(msg) r = await pr.response return pr, r except ConstructionRenderableError as e: raise ClientError("There was an error with the request.", e) except RequestTimedOut as e: await self._reset_protocol(e) raise RequestTimeout('Request timed out.', e) except (OSError, socket.gaierror, Error) as e: # aiocoap sometimes raises an OSError/socket.gaierror too. # aiocoap issue #124 await self._reset_protocol(e) raise ServerError("There was an error with the request.", e) except asyncio.CancelledError as e: await self._reset_protocol(e) raise e
python
async def _get_response(self, msg): """Perform the request, get the response.""" try: protocol = await self._get_protocol() pr = protocol.request(msg) r = await pr.response return pr, r except ConstructionRenderableError as e: raise ClientError("There was an error with the request.", e) except RequestTimedOut as e: await self._reset_protocol(e) raise RequestTimeout('Request timed out.', e) except (OSError, socket.gaierror, Error) as e: # aiocoap sometimes raises an OSError/socket.gaierror too. # aiocoap issue #124 await self._reset_protocol(e) raise ServerError("There was an error with the request.", e) except asyncio.CancelledError as e: await self._reset_protocol(e) raise e
[ "async", "def", "_get_response", "(", "self", ",", "msg", ")", ":", "try", ":", "protocol", "=", "await", "self", ".", "_get_protocol", "(", ")", "pr", "=", "protocol", ".", "request", "(", "msg", ")", "r", "=", "await", "pr", ".", "response", "retur...
Perform the request, get the response.
[ "Perform", "the", "request", "get", "the", "response", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/api/aiocoap_api.py#L90-L109
train
206,728
ggravlingen/pytradfri
pytradfri/group.py
Group.member_ids
def member_ids(self): """Members of this group.""" info = self.raw.get(ATTR_MEMBERS, {}) if not info or ROOT_DEVICES2 not in info: return [] return info[ROOT_DEVICES2].get(ATTR_ID, [])
python
def member_ids(self): """Members of this group.""" info = self.raw.get(ATTR_MEMBERS, {}) if not info or ROOT_DEVICES2 not in info: return [] return info[ROOT_DEVICES2].get(ATTR_ID, [])
[ "def", "member_ids", "(", "self", ")", ":", "info", "=", "self", ".", "raw", ".", "get", "(", "ATTR_MEMBERS", ",", "{", "}", ")", "if", "not", "info", "or", "ROOT_DEVICES2", "not", "in", "info", ":", "return", "[", "]", "return", "info", "[", "ROOT...
Members of this group.
[ "Members", "of", "this", "group", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/group.py#L36-L43
train
206,729
ggravlingen/pytradfri
pytradfri/group.py
Group.set_dimmer
def set_dimmer(self, dimmer, transition_time=None): """Set dimmer value of a group. dimmer: Integer between 0..255 transition_time: Integer representing tenth of a second (default None) """ values = { ATTR_LIGHT_DIMMER: dimmer, } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values)
python
def set_dimmer(self, dimmer, transition_time=None): """Set dimmer value of a group. dimmer: Integer between 0..255 transition_time: Integer representing tenth of a second (default None) """ values = { ATTR_LIGHT_DIMMER: dimmer, } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values)
[ "def", "set_dimmer", "(", "self", ",", "dimmer", ",", "transition_time", "=", "None", ")", ":", "values", "=", "{", "ATTR_LIGHT_DIMMER", ":", "dimmer", ",", "}", "if", "transition_time", "is", "not", "None", ":", "values", "[", "ATTR_TRANSITION_TIME", "]", ...
Set dimmer value of a group. dimmer: Integer between 0..255 transition_time: Integer representing tenth of a second (default None)
[ "Set", "dimmer", "value", "of", "a", "group", "." ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/group.py#L70-L81
train
206,730
ggravlingen/pytradfri
examples/debug_info.py
print_gateway
def print_gateway(): """Print gateway info as JSON""" print("Printing information about the Gateway") data = api(gateway.get_gateway_info()).raw print(jsonify(data))
python
def print_gateway(): """Print gateway info as JSON""" print("Printing information about the Gateway") data = api(gateway.get_gateway_info()).raw print(jsonify(data))
[ "def", "print_gateway", "(", ")", ":", "print", "(", "\"Printing information about the Gateway\"", ")", "data", "=", "api", "(", "gateway", ".", "get_gateway_info", "(", ")", ")", ".", "raw", "print", "(", "jsonify", "(", "data", ")", ")" ]
Print gateway info as JSON
[ "Print", "gateway", "info", "as", "JSON" ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/examples/debug_info.py#L89-L93
train
206,731
ggravlingen/pytradfri
examples/debug_info.py
print_all_devices
def print_all_devices(): """Print all devices as JSON""" print("Printing information about all devices paired to the Gateway") if len(devices) == 0: exit(bold("No devices paired")) container = [] for dev in devices: container.append(dev.raw) print(jsonify(container))
python
def print_all_devices(): """Print all devices as JSON""" print("Printing information about all devices paired to the Gateway") if len(devices) == 0: exit(bold("No devices paired")) container = [] for dev in devices: container.append(dev.raw) print(jsonify(container))
[ "def", "print_all_devices", "(", ")", ":", "print", "(", "\"Printing information about all devices paired to the Gateway\"", ")", "if", "len", "(", "devices", ")", "==", "0", ":", "exit", "(", "bold", "(", "\"No devices paired\"", ")", ")", "container", "=", "[", ...
Print all devices as JSON
[ "Print", "all", "devices", "as", "JSON" ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/examples/debug_info.py#L103-L112
train
206,732
ggravlingen/pytradfri
examples/debug_info.py
print_lamps
def print_lamps(): """Print all lamp devices as JSON""" print("Printing information about all lamps paired to the Gateway") lights = [dev for dev in devices if dev.has_light_control] if len(lights) == 0: exit(bold("No lamps paired")) container = [] for l in lights: container.append(l.raw) print(jsonify(container))
python
def print_lamps(): """Print all lamp devices as JSON""" print("Printing information about all lamps paired to the Gateway") lights = [dev for dev in devices if dev.has_light_control] if len(lights) == 0: exit(bold("No lamps paired")) container = [] for l in lights: container.append(l.raw) print(jsonify(container))
[ "def", "print_lamps", "(", ")", ":", "print", "(", "\"Printing information about all lamps paired to the Gateway\"", ")", "lights", "=", "[", "dev", "for", "dev", "in", "devices", "if", "dev", ".", "has_light_control", "]", "if", "len", "(", "lights", ")", "==",...
Print all lamp devices as JSON
[ "Print", "all", "lamp", "devices", "as", "JSON" ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/examples/debug_info.py#L115-L125
train
206,733
ggravlingen/pytradfri
examples/debug_info.py
print_smart_tasks
def print_smart_tasks(): """Print smart tasks as JSON""" print("Printing information about smart tasks") tasks = api(gateway.get_smart_tasks()) if len(tasks) == 0: exit(bold("No smart tasks defined")) container = [] for task in tasks: container.append(api(task).task_control.raw) print(jsonify(container))
python
def print_smart_tasks(): """Print smart tasks as JSON""" print("Printing information about smart tasks") tasks = api(gateway.get_smart_tasks()) if len(tasks) == 0: exit(bold("No smart tasks defined")) container = [] for task in tasks: container.append(api(task).task_control.raw) print(jsonify(container))
[ "def", "print_smart_tasks", "(", ")", ":", "print", "(", "\"Printing information about smart tasks\"", ")", "tasks", "=", "api", "(", "gateway", ".", "get_smart_tasks", "(", ")", ")", "if", "len", "(", "tasks", ")", "==", "0", ":", "exit", "(", "bold", "("...
Print smart tasks as JSON
[ "Print", "smart", "tasks", "as", "JSON" ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/examples/debug_info.py#L128-L138
train
206,734
ggravlingen/pytradfri
examples/debug_info.py
print_groups
def print_groups(): """Print all groups as JSON""" print("Printing information about all groups defined in the Gateway") groups = api(gateway.get_groups()) if len(groups) == 0: exit(bold("No groups defined")) container = [] for group in groups: container.append(api(group).raw) print(jsonify(container))
python
def print_groups(): """Print all groups as JSON""" print("Printing information about all groups defined in the Gateway") groups = api(gateway.get_groups()) if len(groups) == 0: exit(bold("No groups defined")) container = [] for group in groups: container.append(api(group).raw) print(jsonify(container))
[ "def", "print_groups", "(", ")", ":", "print", "(", "\"Printing information about all groups defined in the Gateway\"", ")", "groups", "=", "api", "(", "gateway", ".", "get_groups", "(", ")", ")", "if", "len", "(", "groups", ")", "==", "0", ":", "exit", "(", ...
Print all groups as JSON
[ "Print", "all", "groups", "as", "JSON" ]
63750fa8fb27158c013d24865cdaa7fb82b3ab53
https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/examples/debug_info.py#L141-L151
train
206,735
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
LoadGDAL
def LoadGDAL(filename, no_data=None): """Read a GDAL file. Opens any file GDAL can read, selects the first raster band, and loads it and its metadata into a RichDEM array of the appropriate data type. If you need to do something more complicated, look at the source of this function. Args: filename (str): Name of the raster file to open no_data (float): Optionally, set the no_data value to this. Returns: A RichDEM array """ if not GDAL_AVAILABLE: raise Exception("richdem.LoadGDAL() requires GDAL.") allowed_types = {gdal.GDT_Byte,gdal.GDT_Int16,gdal.GDT_Int32,gdal.GDT_UInt16,gdal.GDT_UInt32,gdal.GDT_Float32,gdal.GDT_Float64} #Read in data src_ds = gdal.Open(filename) srcband = src_ds.GetRasterBand(1) if no_data is None: no_data = srcband.GetNoDataValue() if no_data is None: raise Exception("The source data did not have a NoData value. Please use the no_data argument to specify one. If should not be equal to any of the actual data values. If you are using all possible data values, then the situation is pretty hopeless - sorry.") srcdata = rdarray(srcband.ReadAsArray(), no_data=no_data) # raster_srs = osr.SpatialReference() # raster_srs.ImportFromWkt(raster.GetProjectionRef()) if not srcband.DataType in allowed_types: raise Exception("This datatype is not supported. Please file a bug report on RichDEM.") srcdata.projection = src_ds.GetProjectionRef() srcdata.geotransform = src_ds.GetGeoTransform() srcdata.metadata = dict() for k,v in src_ds.GetMetadata().items(): srcdata.metadata[k] = v _AddAnalysis(srcdata, "LoadGDAL(filename={0}, no_data={1})".format(filename, no_data)) return srcdata
python
def LoadGDAL(filename, no_data=None): """Read a GDAL file. Opens any file GDAL can read, selects the first raster band, and loads it and its metadata into a RichDEM array of the appropriate data type. If you need to do something more complicated, look at the source of this function. Args: filename (str): Name of the raster file to open no_data (float): Optionally, set the no_data value to this. Returns: A RichDEM array """ if not GDAL_AVAILABLE: raise Exception("richdem.LoadGDAL() requires GDAL.") allowed_types = {gdal.GDT_Byte,gdal.GDT_Int16,gdal.GDT_Int32,gdal.GDT_UInt16,gdal.GDT_UInt32,gdal.GDT_Float32,gdal.GDT_Float64} #Read in data src_ds = gdal.Open(filename) srcband = src_ds.GetRasterBand(1) if no_data is None: no_data = srcband.GetNoDataValue() if no_data is None: raise Exception("The source data did not have a NoData value. Please use the no_data argument to specify one. If should not be equal to any of the actual data values. If you are using all possible data values, then the situation is pretty hopeless - sorry.") srcdata = rdarray(srcband.ReadAsArray(), no_data=no_data) # raster_srs = osr.SpatialReference() # raster_srs.ImportFromWkt(raster.GetProjectionRef()) if not srcband.DataType in allowed_types: raise Exception("This datatype is not supported. Please file a bug report on RichDEM.") srcdata.projection = src_ds.GetProjectionRef() srcdata.geotransform = src_ds.GetGeoTransform() srcdata.metadata = dict() for k,v in src_ds.GetMetadata().items(): srcdata.metadata[k] = v _AddAnalysis(srcdata, "LoadGDAL(filename={0}, no_data={1})".format(filename, no_data)) return srcdata
[ "def", "LoadGDAL", "(", "filename", ",", "no_data", "=", "None", ")", ":", "if", "not", "GDAL_AVAILABLE", ":", "raise", "Exception", "(", "\"richdem.LoadGDAL() requires GDAL.\"", ")", "allowed_types", "=", "{", "gdal", ".", "GDT_Byte", ",", "gdal", ".", "GDT_I...
Read a GDAL file. Opens any file GDAL can read, selects the first raster band, and loads it and its metadata into a RichDEM array of the appropriate data type. If you need to do something more complicated, look at the source of this function. Args: filename (str): Name of the raster file to open no_data (float): Optionally, set the no_data value to this. Returns: A RichDEM array
[ "Read", "a", "GDAL", "file", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L238-L285
train
206,736
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
SaveGDAL
def SaveGDAL(filename, rda): """Save a GDAL file. Saves a RichDEM array to a data file in GeoTIFF format. If you need to do something more complicated, look at the source of this function. Args: filename (str): Name of the raster file to be created rda (rdarray): Data to save. Returns: No Return """ if type(rda) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if not GDAL_AVAILABLE: raise Exception("richdem.SaveGDAL() requires GDAL.") driver = gdal.GetDriverByName('GTiff') data_type = gdal.GDT_Float32 #TODO data_set = driver.Create(filename, xsize=rda.shape[1], ysize=rda.shape[0], bands=1, eType=data_type) data_set.SetGeoTransform(rda.geotransform) data_set.SetProjection(rda.projection) band = data_set.GetRasterBand(1) band.SetNoDataValue(rda.no_data) band.WriteArray(np.array(rda)) for k,v in rda.metadata.items(): data_set.SetMetadataItem(str(k),str(v))
python
def SaveGDAL(filename, rda): """Save a GDAL file. Saves a RichDEM array to a data file in GeoTIFF format. If you need to do something more complicated, look at the source of this function. Args: filename (str): Name of the raster file to be created rda (rdarray): Data to save. Returns: No Return """ if type(rda) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if not GDAL_AVAILABLE: raise Exception("richdem.SaveGDAL() requires GDAL.") driver = gdal.GetDriverByName('GTiff') data_type = gdal.GDT_Float32 #TODO data_set = driver.Create(filename, xsize=rda.shape[1], ysize=rda.shape[0], bands=1, eType=data_type) data_set.SetGeoTransform(rda.geotransform) data_set.SetProjection(rda.projection) band = data_set.GetRasterBand(1) band.SetNoDataValue(rda.no_data) band.WriteArray(np.array(rda)) for k,v in rda.metadata.items(): data_set.SetMetadataItem(str(k),str(v))
[ "def", "SaveGDAL", "(", "filename", ",", "rda", ")", ":", "if", "type", "(", "rda", ")", "is", "not", "rdarray", ":", "raise", "Exception", "(", "\"A richdem.rdarray or numpy.ndarray is required!\"", ")", "if", "not", "GDAL_AVAILABLE", ":", "raise", "Exception",...
Save a GDAL file. Saves a RichDEM array to a data file in GeoTIFF format. If you need to do something more complicated, look at the source of this function. Args: filename (str): Name of the raster file to be created rda (rdarray): Data to save. Returns: No Return
[ "Save", "a", "GDAL", "file", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L289-L319
train
206,737
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
FillDepressions
def FillDepressions( dem, epsilon = False, in_place = False, topology = 'D8' ): """Fills all depressions in a DEM. Args: dem (rdarray): An elevation model epsilon (float): If True, an epsilon gradient is imposed to all flat regions. This ensures that there is always a local gradient. in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if topology not in ['D8','D4']: raise Exception("Unknown topology!") if not in_place: dem = dem.copy() _AddAnalysis(dem, "FillDepressions(dem, epsilon={0})".format(epsilon)) demw = dem.wrap() if epsilon: if topology=='D8': _richdem.rdPFepsilonD8(demw) elif topology=='D4': _richdem.rdPFepsilonD4(demw) else: if topology=='D8': _richdem.rdFillDepressionsD8(demw) elif topology=='D4': _richdem.rdFillDepressionsD4(demw) dem.copyFromWrapped(demw) if not in_place: return dem
python
def FillDepressions( dem, epsilon = False, in_place = False, topology = 'D8' ): """Fills all depressions in a DEM. Args: dem (rdarray): An elevation model epsilon (float): If True, an epsilon gradient is imposed to all flat regions. This ensures that there is always a local gradient. in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if topology not in ['D8','D4']: raise Exception("Unknown topology!") if not in_place: dem = dem.copy() _AddAnalysis(dem, "FillDepressions(dem, epsilon={0})".format(epsilon)) demw = dem.wrap() if epsilon: if topology=='D8': _richdem.rdPFepsilonD8(demw) elif topology=='D4': _richdem.rdPFepsilonD4(demw) else: if topology=='D8': _richdem.rdFillDepressionsD8(demw) elif topology=='D4': _richdem.rdFillDepressionsD4(demw) dem.copyFromWrapped(demw) if not in_place: return dem
[ "def", "FillDepressions", "(", "dem", ",", "epsilon", "=", "False", ",", "in_place", "=", "False", ",", "topology", "=", "'D8'", ")", ":", "if", "type", "(", "dem", ")", "is", "not", "rdarray", ":", "raise", "Exception", "(", "\"A richdem.rdarray or numpy....
Fills all depressions in a DEM. Args: dem (rdarray): An elevation model epsilon (float): If True, an epsilon gradient is imposed to all flat regions. This ensures that there is always a local gradient. in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions.
[ "Fills", "all", "depressions", "in", "a", "DEM", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L323-L369
train
206,738
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
BreachDepressions
def BreachDepressions( dem, in_place = False, topology = 'D8' ): """Breaches all depressions in a DEM. Args: dem (rdarray): An elevation model in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if topology not in ['D8','D4']: raise Exception("Unknown topology!") if not in_place: dem = dem.copy() _AddAnalysis(dem, "BreachDepressions(dem)") demw = dem.wrap() if topology=='D8': _richdem.rdBreachDepressionsD8(demw) elif topology=='D4': _richdem.rdBreachDepressionsD4(demw) dem.copyFromWrapped(demw) if not in_place: return dem
python
def BreachDepressions( dem, in_place = False, topology = 'D8' ): """Breaches all depressions in a DEM. Args: dem (rdarray): An elevation model in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if topology not in ['D8','D4']: raise Exception("Unknown topology!") if not in_place: dem = dem.copy() _AddAnalysis(dem, "BreachDepressions(dem)") demw = dem.wrap() if topology=='D8': _richdem.rdBreachDepressionsD8(demw) elif topology=='D4': _richdem.rdBreachDepressionsD4(demw) dem.copyFromWrapped(demw) if not in_place: return dem
[ "def", "BreachDepressions", "(", "dem", ",", "in_place", "=", "False", ",", "topology", "=", "'D8'", ")", ":", "if", "type", "(", "dem", ")", "is", "not", "rdarray", ":", "raise", "Exception", "(", "\"A richdem.rdarray or numpy.ndarray is required!\"", ")", "i...
Breaches all depressions in a DEM. Args: dem (rdarray): An elevation model in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions.
[ "Breaches", "all", "depressions", "in", "a", "DEM", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L373-L410
train
206,739
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
ResolveFlats
def ResolveFlats( dem, in_place = False ): """Attempts to resolve flats by imposing a local gradient Args: dem (rdarray): An elevation model in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. Returns: DEM modified such that all flats drain. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if not in_place: dem = dem.copy() _AddAnalysis(dem, "ResolveFlats(dem, in_place={in_place})".format(in_place=in_place)) demw = dem.wrap() _richdem.rdResolveFlatsEpsilon(demw) dem.copyFromWrapped(demw) if not in_place: return dem
python
def ResolveFlats( dem, in_place = False ): """Attempts to resolve flats by imposing a local gradient Args: dem (rdarray): An elevation model in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. Returns: DEM modified such that all flats drain. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if not in_place: dem = dem.copy() _AddAnalysis(dem, "ResolveFlats(dem, in_place={in_place})".format(in_place=in_place)) demw = dem.wrap() _richdem.rdResolveFlatsEpsilon(demw) dem.copyFromWrapped(demw) if not in_place: return dem
[ "def", "ResolveFlats", "(", "dem", ",", "in_place", "=", "False", ")", ":", "if", "type", "(", "dem", ")", "is", "not", "rdarray", ":", "raise", "Exception", "(", "\"A richdem.rdarray or numpy.ndarray is required!\"", ")", "if", "not", "in_place", ":", "dem", ...
Attempts to resolve flats by imposing a local gradient Args: dem (rdarray): An elevation model in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. Returns: DEM modified such that all flats drain.
[ "Attempts", "to", "resolve", "flats", "by", "imposing", "a", "local", "gradient" ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L414-L443
train
206,740
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
FlowAccumulation
def FlowAccumulation( dem, method = None, exponent = None, weights = None, in_place = False ): """Calculates flow accumulation. A variety of methods are available. Args: dem (rdarray): An elevation model method (str): Flow accumulation method to use. (See below.) exponent (float): Some methods require an exponent; refer to the relevant publications for details. weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated by each cell. If this is not provided, each cell will generate 1 unit of flow. in_place (bool): If True, then `weights` is modified in place. An accumulation matrix is always returned, but it will just be a view of the modified data if `in_place` is True. =================== ============================== =========================== Method Note Reference =================== ============================== =========================== Tarboton Alias for Dinf. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Dinf Alias for Tarboton. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Quinn Holmgren with exponent=1. `Quinn et al. (1991) doi: 10.1002/hyp.3360050106 <http://dx.doi.org/10.1002/hyp.3360050106>`_ Holmgren(E) Generalization of Quinn. `Holmgren (1994) doi: 10.1002/hyp.3360080405 <http://dx.doi.org/10.1002/hyp.3360080405>`_ Freeman(E) TODO `Freeman (1991) doi: 10.1016/0098-3004(91)90048-I <http://dx.doi.org/10.1016/0098-3004(91)90048-I>`_ FairfieldLeymarieD8 Alias for Rho8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ FairfieldLeymarieD4 Alias for Rho4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho8 Alias for FairfieldLeymarieD8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho4 Alias for FairfieldLeymarieD4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ OCallaghanD8 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ OCallaghanD4 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D8 Alias for OCallaghanD8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D4 Alias for OCallaghanD4. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ =================== ============================== =========================== **Methods marked (E) require the exponent argument.** Returns: A flow accumulation according to the desired method. If `weights` was provided and `in_place` was True, then this matrix is a view of the modified data. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") facc_methods = { "Tarboton": _richdem.FA_Tarboton, "Dinf": _richdem.FA_Tarboton, "Quinn": _richdem.FA_Quinn, "FairfieldLeymarieD8": _richdem.FA_FairfieldLeymarieD8, "FairfieldLeymarieD4": _richdem.FA_FairfieldLeymarieD4, "Rho8": _richdem.FA_Rho8, "Rho4": _richdem.FA_Rho4, "OCallaghanD8": _richdem.FA_OCallaghanD8, "OCallaghanD4": _richdem.FA_OCallaghanD4, "D8": _richdem.FA_D8, "D4": _richdem.FA_D4 } facc_methods_exponent = { "Freeman": _richdem.FA_Freeman, "Holmgren": _richdem.FA_Holmgren } if weights is not None and in_place: accum = rdarray(weights, no_data=-1) elif weights is not None and not in_place: accum = rdarray(weights, copy=True, meta_obj=dem, no_data=-1) elif weights is None: accum = rdarray(np.ones(shape=dem.shape, dtype='float64'), meta_obj=dem, no_data=-1) else: raise Exception("Execution should never reach this point!") if accum.dtype!='float64': raise Exception("Accumulation array must be of type 'float64'!") accumw = accum.wrap() _AddAnalysis(accum, "FlowAccumulation(dem, method={method}, exponent={exponent}, weights={weights}, in_place={in_place})".format( method = method, exponent = exponent, weights = 'None' if weights is None else 'weights', in_place = in_place )) if method in facc_methods: facc_methods[method](dem.wrap(),accumw) elif method in facc_methods_exponent: if exponent is None: raise Exception('FlowAccumulation method "'+method+'" requires an exponent!') facc_methods_exponent[method](dem.wrap(),accumw,exponent) else: raise Exception("Invalid FlowAccumulation method. Valid methods are: " + ', '.join(list(facc_methods.keys()) + list(facc_methods_exponent.keys()) )) accum.copyFromWrapped(accumw) return accum
python
def FlowAccumulation( dem, method = None, exponent = None, weights = None, in_place = False ): """Calculates flow accumulation. A variety of methods are available. Args: dem (rdarray): An elevation model method (str): Flow accumulation method to use. (See below.) exponent (float): Some methods require an exponent; refer to the relevant publications for details. weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated by each cell. If this is not provided, each cell will generate 1 unit of flow. in_place (bool): If True, then `weights` is modified in place. An accumulation matrix is always returned, but it will just be a view of the modified data if `in_place` is True. =================== ============================== =========================== Method Note Reference =================== ============================== =========================== Tarboton Alias for Dinf. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Dinf Alias for Tarboton. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Quinn Holmgren with exponent=1. `Quinn et al. (1991) doi: 10.1002/hyp.3360050106 <http://dx.doi.org/10.1002/hyp.3360050106>`_ Holmgren(E) Generalization of Quinn. `Holmgren (1994) doi: 10.1002/hyp.3360080405 <http://dx.doi.org/10.1002/hyp.3360080405>`_ Freeman(E) TODO `Freeman (1991) doi: 10.1016/0098-3004(91)90048-I <http://dx.doi.org/10.1016/0098-3004(91)90048-I>`_ FairfieldLeymarieD8 Alias for Rho8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ FairfieldLeymarieD4 Alias for Rho4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho8 Alias for FairfieldLeymarieD8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho4 Alias for FairfieldLeymarieD4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ OCallaghanD8 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ OCallaghanD4 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D8 Alias for OCallaghanD8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D4 Alias for OCallaghanD4. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ =================== ============================== =========================== **Methods marked (E) require the exponent argument.** Returns: A flow accumulation according to the desired method. If `weights` was provided and `in_place` was True, then this matrix is a view of the modified data. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") facc_methods = { "Tarboton": _richdem.FA_Tarboton, "Dinf": _richdem.FA_Tarboton, "Quinn": _richdem.FA_Quinn, "FairfieldLeymarieD8": _richdem.FA_FairfieldLeymarieD8, "FairfieldLeymarieD4": _richdem.FA_FairfieldLeymarieD4, "Rho8": _richdem.FA_Rho8, "Rho4": _richdem.FA_Rho4, "OCallaghanD8": _richdem.FA_OCallaghanD8, "OCallaghanD4": _richdem.FA_OCallaghanD4, "D8": _richdem.FA_D8, "D4": _richdem.FA_D4 } facc_methods_exponent = { "Freeman": _richdem.FA_Freeman, "Holmgren": _richdem.FA_Holmgren } if weights is not None and in_place: accum = rdarray(weights, no_data=-1) elif weights is not None and not in_place: accum = rdarray(weights, copy=True, meta_obj=dem, no_data=-1) elif weights is None: accum = rdarray(np.ones(shape=dem.shape, dtype='float64'), meta_obj=dem, no_data=-1) else: raise Exception("Execution should never reach this point!") if accum.dtype!='float64': raise Exception("Accumulation array must be of type 'float64'!") accumw = accum.wrap() _AddAnalysis(accum, "FlowAccumulation(dem, method={method}, exponent={exponent}, weights={weights}, in_place={in_place})".format( method = method, exponent = exponent, weights = 'None' if weights is None else 'weights', in_place = in_place )) if method in facc_methods: facc_methods[method](dem.wrap(),accumw) elif method in facc_methods_exponent: if exponent is None: raise Exception('FlowAccumulation method "'+method+'" requires an exponent!') facc_methods_exponent[method](dem.wrap(),accumw,exponent) else: raise Exception("Invalid FlowAccumulation method. Valid methods are: " + ', '.join(list(facc_methods.keys()) + list(facc_methods_exponent.keys()) )) accum.copyFromWrapped(accumw) return accum
[ "def", "FlowAccumulation", "(", "dem", ",", "method", "=", "None", ",", "exponent", "=", "None", ",", "weights", "=", "None", ",", "in_place", "=", "False", ")", ":", "if", "type", "(", "dem", ")", "is", "not", "rdarray", ":", "raise", "Exception", "...
Calculates flow accumulation. A variety of methods are available. Args: dem (rdarray): An elevation model method (str): Flow accumulation method to use. (See below.) exponent (float): Some methods require an exponent; refer to the relevant publications for details. weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated by each cell. If this is not provided, each cell will generate 1 unit of flow. in_place (bool): If True, then `weights` is modified in place. An accumulation matrix is always returned, but it will just be a view of the modified data if `in_place` is True. =================== ============================== =========================== Method Note Reference =================== ============================== =========================== Tarboton Alias for Dinf. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Dinf Alias for Tarboton. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Quinn Holmgren with exponent=1. `Quinn et al. (1991) doi: 10.1002/hyp.3360050106 <http://dx.doi.org/10.1002/hyp.3360050106>`_ Holmgren(E) Generalization of Quinn. `Holmgren (1994) doi: 10.1002/hyp.3360080405 <http://dx.doi.org/10.1002/hyp.3360080405>`_ Freeman(E) TODO `Freeman (1991) doi: 10.1016/0098-3004(91)90048-I <http://dx.doi.org/10.1016/0098-3004(91)90048-I>`_ FairfieldLeymarieD8 Alias for Rho8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ FairfieldLeymarieD4 Alias for Rho4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho8 Alias for FairfieldLeymarieD8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho4 Alias for FairfieldLeymarieD4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ OCallaghanD8 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ OCallaghanD4 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D8 Alias for OCallaghanD8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D4 Alias for OCallaghanD4. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ =================== ============================== =========================== **Methods marked (E) require the exponent argument.** Returns: A flow accumulation according to the desired method. If `weights` was provided and `in_place` was True, then this matrix is a view of the modified data.
[ "Calculates", "flow", "accumulation", ".", "A", "variety", "of", "methods", "are", "available", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L447-L549
train
206,741
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
FlowAccumFromProps
def FlowAccumFromProps( props, weights = None, in_place = False ): """Calculates flow accumulation from flow proportions. Args: props (rdarray): An elevation model weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated by each cell. If this is not provided, each cell will generate 1 unit of flow. in_place (bool): If True, then `weights` is modified in place. An accumulation matrix is always returned, but it will just be a view of the modified data if `in_place` is True. Returns: A flow accumulation array. If `weights` was provided and `in_place` was True, then this matrix is a view of the modified data. """ if type(props) is not rd3array: raise Exception("A richdem.rd3array or numpy.ndarray is required!") if weights is not None and in_place: accum = rdarray(weights, no_data=-1) elif weights is not None and not in_place: accum = rdarray(weights, copy=True, meta_obj=props, no_data=-1) elif weights is None: accum = rdarray(np.ones(shape=props.shape[0:2], dtype='float64'), meta_obj=props, no_data=-1) else: raise Exception("Execution should never reach this point!") if accum.dtype!='float64': raise Exception("Accumulation array must be of type 'float64'!") accumw = accum.wrap() _AddAnalysis(accum, "FlowAccumFromProps(dem, weights={weights}, in_place={in_place})".format( weights = 'None' if weights is None else 'weights', in_place = in_place )) _richdem.FlowAccumulation(props.wrap(),accumw) accum.copyFromWrapped(accumw) return accum
python
def FlowAccumFromProps( props, weights = None, in_place = False ): """Calculates flow accumulation from flow proportions. Args: props (rdarray): An elevation model weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated by each cell. If this is not provided, each cell will generate 1 unit of flow. in_place (bool): If True, then `weights` is modified in place. An accumulation matrix is always returned, but it will just be a view of the modified data if `in_place` is True. Returns: A flow accumulation array. If `weights` was provided and `in_place` was True, then this matrix is a view of the modified data. """ if type(props) is not rd3array: raise Exception("A richdem.rd3array or numpy.ndarray is required!") if weights is not None and in_place: accum = rdarray(weights, no_data=-1) elif weights is not None and not in_place: accum = rdarray(weights, copy=True, meta_obj=props, no_data=-1) elif weights is None: accum = rdarray(np.ones(shape=props.shape[0:2], dtype='float64'), meta_obj=props, no_data=-1) else: raise Exception("Execution should never reach this point!") if accum.dtype!='float64': raise Exception("Accumulation array must be of type 'float64'!") accumw = accum.wrap() _AddAnalysis(accum, "FlowAccumFromProps(dem, weights={weights}, in_place={in_place})".format( weights = 'None' if weights is None else 'weights', in_place = in_place )) _richdem.FlowAccumulation(props.wrap(),accumw) accum.copyFromWrapped(accumw) return accum
[ "def", "FlowAccumFromProps", "(", "props", ",", "weights", "=", "None", ",", "in_place", "=", "False", ")", ":", "if", "type", "(", "props", ")", "is", "not", "rd3array", ":", "raise", "Exception", "(", "\"A richdem.rd3array or numpy.ndarray is required!\"", ")"...
Calculates flow accumulation from flow proportions. Args: props (rdarray): An elevation model weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated by each cell. If this is not provided, each cell will generate 1 unit of flow. in_place (bool): If True, then `weights` is modified in place. An accumulation matrix is always returned, but it will just be a view of the modified data if `in_place` is True. Returns: A flow accumulation array. If `weights` was provided and `in_place` was True, then this matrix is a view of the modified data.
[ "Calculates", "flow", "accumulation", "from", "flow", "proportions", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L553-L601
train
206,742
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
FlowProportions
def FlowProportions( dem, method = None, exponent = None ): """Calculates flow proportions. A variety of methods are available. Args: dem (rdarray): An elevation model method (str): Flow accumulation method to use. (See below.) exponent (float): Some methods require an exponent; refer to the relevant publications for details. =================== ============================== =========================== Method Note Reference =================== ============================== =========================== Tarboton Alias for Dinf. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Dinf Alias for Tarboton. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Quinn Holmgren with exponent=1. `Quinn et al. (1991) doi: 10.1002/hyp.3360050106 <http://dx.doi.org/10.1002/hyp.3360050106>`_ Holmgren(E) Generalization of Quinn. `Holmgren (1994) doi: 10.1002/hyp.3360080405 <http://dx.doi.org/10.1002/hyp.3360080405>`_ Freeman(E) TODO `Freeman (1991) doi: 10.1016/0098-3004(91)90048-I <http://dx.doi.org/10.1016/0098-3004(91)90048-I>`_ FairfieldLeymarieD8 Alias for Rho8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ FairfieldLeymarieD4 Alias for Rho4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho8 Alias for FairfieldLeymarieD8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho4 Alias for FairfieldLeymarieD4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ OCallaghanD8 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ OCallaghanD4 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D8 Alias for OCallaghanD8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D4 Alias for OCallaghanD4. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ =================== ============================== =========================== **Methods marked (E) require the exponent argument.** Returns: A flow proportion according to the desired method. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") fprop_methods = { "Tarboton": _richdem.FM_Tarboton, "Dinf": _richdem.FM_Tarboton, "Quinn": _richdem.FM_Quinn, "FairfieldLeymarieD8": _richdem.FM_FairfieldLeymarieD8, "FairfieldLeymarieD4": _richdem.FM_FairfieldLeymarieD4, "Rho8": _richdem.FM_Rho8, "Rho4": _richdem.FM_Rho4, "OCallaghanD8": _richdem.FM_OCallaghanD8, "OCallaghanD4": _richdem.FM_OCallaghanD4, "D8": _richdem.FM_D8, "D4": _richdem.FM_D4 } fprop_methods_exponent = { "Freeman": _richdem.FM_Freeman, "Holmgren": _richdem.FM_Holmgren } fprops = rd3array(np.zeros(shape=dem.shape+(9,), dtype='float32'), meta_obj=dem, no_data=-2) fpropsw = fprops.wrap() _AddAnalysis(fprops, "FlowProportions(dem, method={method}, exponent={exponent})".format( method = method, exponent = exponent, )) if method in fprop_methods: fprop_methods[method](dem.wrap(),fpropsw) elif method in fprop_methods_exponent: if exponent is None: raise Exception('FlowProportions method "'+method+'" requires an exponent!') fprop_methods_exponent[method](dem.wrap(),fpropsw,exponent) else: raise Exception("Invalid FlowProportions method. Valid methods are: " + ', '.join(list(fprop_methods.keys()) + list(fprop_methods_exponent.keys()) )) fprops.copyFromWrapped(fpropsw) return fprops
python
def FlowProportions( dem, method = None, exponent = None ): """Calculates flow proportions. A variety of methods are available. Args: dem (rdarray): An elevation model method (str): Flow accumulation method to use. (See below.) exponent (float): Some methods require an exponent; refer to the relevant publications for details. =================== ============================== =========================== Method Note Reference =================== ============================== =========================== Tarboton Alias for Dinf. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Dinf Alias for Tarboton. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Quinn Holmgren with exponent=1. `Quinn et al. (1991) doi: 10.1002/hyp.3360050106 <http://dx.doi.org/10.1002/hyp.3360050106>`_ Holmgren(E) Generalization of Quinn. `Holmgren (1994) doi: 10.1002/hyp.3360080405 <http://dx.doi.org/10.1002/hyp.3360080405>`_ Freeman(E) TODO `Freeman (1991) doi: 10.1016/0098-3004(91)90048-I <http://dx.doi.org/10.1016/0098-3004(91)90048-I>`_ FairfieldLeymarieD8 Alias for Rho8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ FairfieldLeymarieD4 Alias for Rho4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho8 Alias for FairfieldLeymarieD8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho4 Alias for FairfieldLeymarieD4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ OCallaghanD8 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ OCallaghanD4 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D8 Alias for OCallaghanD8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D4 Alias for OCallaghanD4. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ =================== ============================== =========================== **Methods marked (E) require the exponent argument.** Returns: A flow proportion according to the desired method. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") fprop_methods = { "Tarboton": _richdem.FM_Tarboton, "Dinf": _richdem.FM_Tarboton, "Quinn": _richdem.FM_Quinn, "FairfieldLeymarieD8": _richdem.FM_FairfieldLeymarieD8, "FairfieldLeymarieD4": _richdem.FM_FairfieldLeymarieD4, "Rho8": _richdem.FM_Rho8, "Rho4": _richdem.FM_Rho4, "OCallaghanD8": _richdem.FM_OCallaghanD8, "OCallaghanD4": _richdem.FM_OCallaghanD4, "D8": _richdem.FM_D8, "D4": _richdem.FM_D4 } fprop_methods_exponent = { "Freeman": _richdem.FM_Freeman, "Holmgren": _richdem.FM_Holmgren } fprops = rd3array(np.zeros(shape=dem.shape+(9,), dtype='float32'), meta_obj=dem, no_data=-2) fpropsw = fprops.wrap() _AddAnalysis(fprops, "FlowProportions(dem, method={method}, exponent={exponent})".format( method = method, exponent = exponent, )) if method in fprop_methods: fprop_methods[method](dem.wrap(),fpropsw) elif method in fprop_methods_exponent: if exponent is None: raise Exception('FlowProportions method "'+method+'" requires an exponent!') fprop_methods_exponent[method](dem.wrap(),fpropsw,exponent) else: raise Exception("Invalid FlowProportions method. Valid methods are: " + ', '.join(list(fprop_methods.keys()) + list(fprop_methods_exponent.keys()) )) fprops.copyFromWrapped(fpropsw) return fprops
[ "def", "FlowProportions", "(", "dem", ",", "method", "=", "None", ",", "exponent", "=", "None", ")", ":", "if", "type", "(", "dem", ")", "is", "not", "rdarray", ":", "raise", "Exception", "(", "\"A richdem.rdarray or numpy.ndarray is required!\"", ")", "fprop_...
Calculates flow proportions. A variety of methods are available. Args: dem (rdarray): An elevation model method (str): Flow accumulation method to use. (See below.) exponent (float): Some methods require an exponent; refer to the relevant publications for details. =================== ============================== =========================== Method Note Reference =================== ============================== =========================== Tarboton Alias for Dinf. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Dinf Alias for Tarboton. `Taroboton (1997) doi: 10.1029/96WR03137 <http://dx.doi.org/10.1029/96WR03137>`_ Quinn Holmgren with exponent=1. `Quinn et al. (1991) doi: 10.1002/hyp.3360050106 <http://dx.doi.org/10.1002/hyp.3360050106>`_ Holmgren(E) Generalization of Quinn. `Holmgren (1994) doi: 10.1002/hyp.3360080405 <http://dx.doi.org/10.1002/hyp.3360080405>`_ Freeman(E) TODO `Freeman (1991) doi: 10.1016/0098-3004(91)90048-I <http://dx.doi.org/10.1016/0098-3004(91)90048-I>`_ FairfieldLeymarieD8 Alias for Rho8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ FairfieldLeymarieD4 Alias for Rho4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho8 Alias for FairfieldLeymarieD8. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ Rho4 Alias for FairfieldLeymarieD4. `Fairfield and Leymarie (1991) doi: 10.1029/90WR02658 <http://dx.doi.org/10.1029/90WR02658>`_ OCallaghanD8 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ OCallaghanD4 Alias for D8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D8 Alias for OCallaghanD8. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ D4 Alias for OCallaghanD4. `O'Callaghan and Mark (1984) doi: 10.1016/S0734-189X(84)80011-0 <http://dx.doi.org/10.1016/S0734-189X(84)80011-0>`_ =================== ============================== =========================== **Methods marked (E) require the exponent argument.** Returns: A flow proportion according to the desired method.
[ "Calculates", "flow", "proportions", ".", "A", "variety", "of", "methods", "are", "available", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L605-L682
train
206,743
r-barnes/richdem
wrappers/pyrichdem/richdem/__init__.py
TerrainAttribute
def TerrainAttribute( dem, attrib, zscale = 1.0 ): """Calculates terrain attributes. A variety of methods are available. Args: dem (rdarray): An elevation model attrib (str): Terrain attribute to calculate. (See below.) zscale (float): How much to scale the z-axis by prior to calculation ======================= ========= Method Reference ======================= ========= slope_riserun `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_percentage `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_degrees `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_radians `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ aspect `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ planform_curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ profile_curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ ======================= ========= Returns: A raster of the indicated terrain attributes. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") terrain_attribs = { #"spi": _richdem.TA_SPI, #"cti": _richdem.TA_CTI, "slope_riserun": _richdem.TA_slope_riserun, "slope_percentage": _richdem.TA_slope_percentage, "slope_degrees": _richdem.TA_slope_degrees, "slope_radians": _richdem.TA_slope_radians, "aspect": _richdem.TA_aspect, "curvature": _richdem.TA_curvature, "planform_curvature": _richdem.TA_planform_curvature, "profile_curvature": _richdem.TA_profile_curvature, } if not attrib in terrain_attribs: raise Exception("Invalid TerrainAttributes attribute. Valid attributes are: " + ', '.join(terrain_attribs.keys())) result = rdarray(np.zeros(shape=dem.shape, dtype='float32'), meta_obj=dem, no_data=-9999) resultw = result.wrap() _AddAnalysis(result, "TerrainAttribute(dem, attrib={0}, zscale={1})".format(attrib,zscale)) terrain_attribs[attrib](dem.wrap(),resultw,zscale) result.copyFromWrapped(resultw) return result
python
def TerrainAttribute( dem, attrib, zscale = 1.0 ): """Calculates terrain attributes. A variety of methods are available. Args: dem (rdarray): An elevation model attrib (str): Terrain attribute to calculate. (See below.) zscale (float): How much to scale the z-axis by prior to calculation ======================= ========= Method Reference ======================= ========= slope_riserun `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_percentage `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_degrees `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_radians `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ aspect `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ planform_curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ profile_curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ ======================= ========= Returns: A raster of the indicated terrain attributes. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") terrain_attribs = { #"spi": _richdem.TA_SPI, #"cti": _richdem.TA_CTI, "slope_riserun": _richdem.TA_slope_riserun, "slope_percentage": _richdem.TA_slope_percentage, "slope_degrees": _richdem.TA_slope_degrees, "slope_radians": _richdem.TA_slope_radians, "aspect": _richdem.TA_aspect, "curvature": _richdem.TA_curvature, "planform_curvature": _richdem.TA_planform_curvature, "profile_curvature": _richdem.TA_profile_curvature, } if not attrib in terrain_attribs: raise Exception("Invalid TerrainAttributes attribute. Valid attributes are: " + ', '.join(terrain_attribs.keys())) result = rdarray(np.zeros(shape=dem.shape, dtype='float32'), meta_obj=dem, no_data=-9999) resultw = result.wrap() _AddAnalysis(result, "TerrainAttribute(dem, attrib={0}, zscale={1})".format(attrib,zscale)) terrain_attribs[attrib](dem.wrap(),resultw,zscale) result.copyFromWrapped(resultw) return result
[ "def", "TerrainAttribute", "(", "dem", ",", "attrib", ",", "zscale", "=", "1.0", ")", ":", "if", "type", "(", "dem", ")", "is", "not", "rdarray", ":", "raise", "Exception", "(", "\"A richdem.rdarray or numpy.ndarray is required!\"", ")", "terrain_attribs", "=", ...
Calculates terrain attributes. A variety of methods are available. Args: dem (rdarray): An elevation model attrib (str): Terrain attribute to calculate. (See below.) zscale (float): How much to scale the z-axis by prior to calculation ======================= ========= Method Reference ======================= ========= slope_riserun `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_percentage `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_degrees `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ slope_radians `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ aspect `Horn (1981) doi: 10.1109/PROC.1981.11918 <http://dx.doi.org/10.1109/PROC.1981.11918>`_ curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ planform_curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ profile_curvature `Zevenbergen and Thorne (1987) doi: 10.1002/esp.3290120107 <http://dx.doi.org/10.1002/esp.3290120107>`_ ======================= ========= Returns: A raster of the indicated terrain attributes.
[ "Calculates", "terrain", "attributes", ".", "A", "variety", "of", "methods", "are", "available", "." ]
abc04d81216d7cf5b57ad7a1e04b5699369b6f58
https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L686-L742
train
206,744
nteract/bookstore
bookstore/s3_paths.py
_join
def _join(*args): """Join S3 bucket args together. Remove empty entries and strip left-leading ``/`` """ return delimiter.join(filter(lambda s: s != '', map(lambda s: s.lstrip(delimiter), args)))
python
def _join(*args): """Join S3 bucket args together. Remove empty entries and strip left-leading ``/`` """ return delimiter.join(filter(lambda s: s != '', map(lambda s: s.lstrip(delimiter), args)))
[ "def", "_join", "(", "*", "args", ")", ":", "return", "delimiter", ".", "join", "(", "filter", "(", "lambda", "s", ":", "s", "!=", "''", ",", "map", "(", "lambda", "s", ":", "s", ".", "lstrip", "(", "delimiter", ")", ",", "args", ")", ")", ")" ...
Join S3 bucket args together. Remove empty entries and strip left-leading ``/``
[ "Join", "S3", "bucket", "args", "together", "." ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/s3_paths.py#L8-L13
train
206,745
nteract/bookstore
bookstore/handlers.py
BookstorePublishHandler.initialize
def initialize(self): """Initialize a helper to get bookstore settings and session information quickly""" self.bookstore_settings = BookstoreSettings(config=self.config) self.session = aiobotocore.get_session()
python
def initialize(self): """Initialize a helper to get bookstore settings and session information quickly""" self.bookstore_settings = BookstoreSettings(config=self.config) self.session = aiobotocore.get_session()
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "bookstore_settings", "=", "BookstoreSettings", "(", "config", "=", "self", ".", "config", ")", "self", ".", "session", "=", "aiobotocore", ".", "get_session", "(", ")" ]
Initialize a helper to get bookstore settings and session information quickly
[ "Initialize", "a", "helper", "to", "get", "bookstore", "settings", "and", "session", "information", "quickly" ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/handlers.py#L48-L51
train
206,746
nteract/bookstore
bookstore/handlers.py
BookstorePublishHandler.put
async def put(self, path=''): """Publish a notebook on a given path. The payload directly matches the contents API for PUT. """ self.log.info("Attempt publishing to %s", path) if path == '' or path == '/': raise web.HTTPError(400, "Must provide a path for publishing") model = self.get_json_body() if model: await self._publish(model, path.lstrip('/')) else: raise web.HTTPError(400, "Cannot publish an empty model")
python
async def put(self, path=''): """Publish a notebook on a given path. The payload directly matches the contents API for PUT. """ self.log.info("Attempt publishing to %s", path) if path == '' or path == '/': raise web.HTTPError(400, "Must provide a path for publishing") model = self.get_json_body() if model: await self._publish(model, path.lstrip('/')) else: raise web.HTTPError(400, "Cannot publish an empty model")
[ "async", "def", "put", "(", "self", ",", "path", "=", "''", ")", ":", "self", ".", "log", ".", "info", "(", "\"Attempt publishing to %s\"", ",", "path", ")", "if", "path", "==", "''", "or", "path", "==", "'/'", ":", "raise", "web", ".", "HTTPError", ...
Publish a notebook on a given path. The payload directly matches the contents API for PUT.
[ "Publish", "a", "notebook", "on", "a", "given", "path", "." ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/handlers.py#L54-L68
train
206,747
nteract/bookstore
bookstore/handlers.py
BookstorePublishHandler._publish
async def _publish(self, model, path): """Publish notebook model to the path""" if model['type'] != 'notebook': raise web.HTTPError(400, "bookstore only publishes notebooks") content = model['content'] full_s3_path = s3_path( self.bookstore_settings.s3_bucket, self.bookstore_settings.published_prefix, path ) file_key = s3_key(self.bookstore_settings.published_prefix, path) self.log.info( "Publishing to %s", s3_display_path( self.bookstore_settings.s3_bucket, self.bookstore_settings.published_prefix, path ), ) async with self.session.create_client( 's3', aws_secret_access_key=self.bookstore_settings.s3_secret_access_key, aws_access_key_id=self.bookstore_settings.s3_access_key_id, endpoint_url=self.bookstore_settings.s3_endpoint_url, region_name=self.bookstore_settings.s3_region_name, ) as client: self.log.info("Processing published write of %s", path) obj = await client.put_object( Bucket=self.bookstore_settings.s3_bucket, Key=file_key, Body=json.dumps(content) ) self.log.info("Done with published write of %s", path) self.set_status(201) resp_content = {"s3path": full_s3_path} if 'VersionId' in obj: resp_content["versionID"] = obj['VersionId'] resp_str = json.dumps(resp_content) self.finish(resp_str)
python
async def _publish(self, model, path): """Publish notebook model to the path""" if model['type'] != 'notebook': raise web.HTTPError(400, "bookstore only publishes notebooks") content = model['content'] full_s3_path = s3_path( self.bookstore_settings.s3_bucket, self.bookstore_settings.published_prefix, path ) file_key = s3_key(self.bookstore_settings.published_prefix, path) self.log.info( "Publishing to %s", s3_display_path( self.bookstore_settings.s3_bucket, self.bookstore_settings.published_prefix, path ), ) async with self.session.create_client( 's3', aws_secret_access_key=self.bookstore_settings.s3_secret_access_key, aws_access_key_id=self.bookstore_settings.s3_access_key_id, endpoint_url=self.bookstore_settings.s3_endpoint_url, region_name=self.bookstore_settings.s3_region_name, ) as client: self.log.info("Processing published write of %s", path) obj = await client.put_object( Bucket=self.bookstore_settings.s3_bucket, Key=file_key, Body=json.dumps(content) ) self.log.info("Done with published write of %s", path) self.set_status(201) resp_content = {"s3path": full_s3_path} if 'VersionId' in obj: resp_content["versionID"] = obj['VersionId'] resp_str = json.dumps(resp_content) self.finish(resp_str)
[ "async", "def", "_publish", "(", "self", ",", "model", ",", "path", ")", ":", "if", "model", "[", "'type'", "]", "!=", "'notebook'", ":", "raise", "web", ".", "HTTPError", "(", "400", ",", "\"bookstore only publishes notebooks\"", ")", "content", "=", "mod...
Publish notebook model to the path
[ "Publish", "notebook", "model", "to", "the", "path" ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/handlers.py#L70-L109
train
206,748
nteract/bookstore
bookstore/client/notebook.py
NotebookClient.setup_auth
def setup_auth(self): """ Sets up token access for authorizing requests to notebook server. This sets the notebook token as self.token and the xsrf_token as self.xsrf_token. """ self.token = self.nb_record.token first = requests.get(f"{self.url}/login") self.xsrf_token = first.cookies.get("_xsrf", "")
python
def setup_auth(self): """ Sets up token access for authorizing requests to notebook server. This sets the notebook token as self.token and the xsrf_token as self.xsrf_token. """ self.token = self.nb_record.token first = requests.get(f"{self.url}/login") self.xsrf_token = first.cookies.get("_xsrf", "")
[ "def", "setup_auth", "(", "self", ")", ":", "self", ".", "token", "=", "self", ".", "nb_record", ".", "token", "first", "=", "requests", ".", "get", "(", "f\"{self.url}/login\"", ")", "self", ".", "xsrf_token", "=", "first", ".", "cookies", ".", "get", ...
Sets up token access for authorizing requests to notebook server. This sets the notebook token as self.token and the xsrf_token as self.xsrf_token.
[ "Sets", "up", "token", "access", "for", "authorizing", "requests", "to", "notebook", "server", "." ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/client/notebook.py#L94-L101
train
206,749
nteract/bookstore
bookstore/client/notebook.py
NotebookClient.setup_request_sessions
def setup_request_sessions(self): """ Sets up a requests.Session object for sharing headers across API requests. """ self.req_session = requests.Session() self.req_session.headers.update(self.headers)
python
def setup_request_sessions(self): """ Sets up a requests.Session object for sharing headers across API requests. """ self.req_session = requests.Session() self.req_session.headers.update(self.headers)
[ "def", "setup_request_sessions", "(", "self", ")", ":", "self", ".", "req_session", "=", "requests", ".", "Session", "(", ")", "self", ".", "req_session", ".", "headers", ".", "update", "(", "self", ".", "headers", ")" ]
Sets up a requests.Session object for sharing headers across API requests.
[ "Sets", "up", "a", "requests", ".", "Session", "object", "for", "sharing", "headers", "across", "API", "requests", "." ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/client/notebook.py#L103-L107
train
206,750
nteract/bookstore
bookstore/archive.py
BookstoreContentsArchiver.archive
async def archive(self, record: ArchiveRecord): """Process a record to write to storage. Acquire a path lock before archive. Writing to storage will only be allowed to a path if a valid `path_lock` is held and the path is not locked by another process. Parameters ---------- record : ArchiveRecord A notebook and where it should be written to storage """ async with self.path_lock_ready: lock = self.path_locks.get(record.filepath) if lock is None: lock = Lock() self.path_locks[record.filepath] = lock # Skip writes when a given path is already locked if lock.locked(): self.log.info("Skipping archive of %s", record.filepath) return async with lock: try: async with self.session.create_client( 's3', aws_secret_access_key=self.settings.s3_secret_access_key, aws_access_key_id=self.settings.s3_access_key_id, endpoint_url=self.settings.s3_endpoint_url, region_name=self.settings.s3_region_name, ) as client: self.log.info("Processing storage write of %s", record.filepath) file_key = s3_key(self.settings.workspace_prefix, record.filepath) await client.put_object( Bucket=self.settings.s3_bucket, Key=file_key, Body=record.content ) self.log.info("Done with storage write of %s", record.filepath) except Exception as e: self.log.error( 'Error while archiving file: %s %s', record.filepath, e, exc_info=True )
python
async def archive(self, record: ArchiveRecord): """Process a record to write to storage. Acquire a path lock before archive. Writing to storage will only be allowed to a path if a valid `path_lock` is held and the path is not locked by another process. Parameters ---------- record : ArchiveRecord A notebook and where it should be written to storage """ async with self.path_lock_ready: lock = self.path_locks.get(record.filepath) if lock is None: lock = Lock() self.path_locks[record.filepath] = lock # Skip writes when a given path is already locked if lock.locked(): self.log.info("Skipping archive of %s", record.filepath) return async with lock: try: async with self.session.create_client( 's3', aws_secret_access_key=self.settings.s3_secret_access_key, aws_access_key_id=self.settings.s3_access_key_id, endpoint_url=self.settings.s3_endpoint_url, region_name=self.settings.s3_region_name, ) as client: self.log.info("Processing storage write of %s", record.filepath) file_key = s3_key(self.settings.workspace_prefix, record.filepath) await client.put_object( Bucket=self.settings.s3_bucket, Key=file_key, Body=record.content ) self.log.info("Done with storage write of %s", record.filepath) except Exception as e: self.log.error( 'Error while archiving file: %s %s', record.filepath, e, exc_info=True )
[ "async", "def", "archive", "(", "self", ",", "record", ":", "ArchiveRecord", ")", ":", "async", "with", "self", ".", "path_lock_ready", ":", "lock", "=", "self", ".", "path_locks", ".", "get", "(", "record", ".", "filepath", ")", "if", "lock", "is", "N...
Process a record to write to storage. Acquire a path lock before archive. Writing to storage will only be allowed to a path if a valid `path_lock` is held and the path is not locked by another process. Parameters ---------- record : ArchiveRecord A notebook and where it should be written to storage
[ "Process", "a", "record", "to", "write", "to", "storage", "." ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/archive.py#L84-L126
train
206,751
nteract/bookstore
bookstore/archive.py
BookstoreContentsArchiver.run_pre_save_hook
def run_pre_save_hook(self, model, path, **kwargs): """Send request to store notebook to S3. This hook offloads the storage request to the event loop. When the event loop is available for execution of the request, the storage of the notebook will be done and the write to storage occurs. Parameters ---------- model : str The type of file path : str The storage location """ if model["type"] != "notebook": return content = json.dumps(model["content"]) loop = ioloop.IOLoop.current() # Offload archival and schedule write to storage with the current event loop loop.spawn_callback( self.archive, ArchiveRecord( content=content, filepath=path, queued_time=ioloop.IOLoop.current().time() ), )
python
def run_pre_save_hook(self, model, path, **kwargs): """Send request to store notebook to S3. This hook offloads the storage request to the event loop. When the event loop is available for execution of the request, the storage of the notebook will be done and the write to storage occurs. Parameters ---------- model : str The type of file path : str The storage location """ if model["type"] != "notebook": return content = json.dumps(model["content"]) loop = ioloop.IOLoop.current() # Offload archival and schedule write to storage with the current event loop loop.spawn_callback( self.archive, ArchiveRecord( content=content, filepath=path, queued_time=ioloop.IOLoop.current().time() ), )
[ "def", "run_pre_save_hook", "(", "self", ",", "model", ",", "path", ",", "*", "*", "kwargs", ")", ":", "if", "model", "[", "\"type\"", "]", "!=", "\"notebook\"", ":", "return", "content", "=", "json", ".", "dumps", "(", "model", "[", "\"content\"", "]"...
Send request to store notebook to S3. This hook offloads the storage request to the event loop. When the event loop is available for execution of the request, the storage of the notebook will be done and the write to storage occurs. Parameters ---------- model : str The type of file path : str The storage location
[ "Send", "request", "to", "store", "notebook", "to", "S3", "." ]
14d90834cc09e211453dbebf8914b9c0819bdcda
https://github.com/nteract/bookstore/blob/14d90834cc09e211453dbebf8914b9c0819bdcda/bookstore/archive.py#L128-L155
train
206,752
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.get
def get(self, url): """ do a get transaction """ return requests.get(url, params=self.data, headers=self.config.HEADERS)
python
def get(self, url): """ do a get transaction """ return requests.get(url, params=self.data, headers=self.config.HEADERS)
[ "def", "get", "(", "self", ",", "url", ")", ":", "return", "requests", ".", "get", "(", "url", ",", "params", "=", "self", ".", "data", ",", "headers", "=", "self", ".", "config", ".", "HEADERS", ")" ]
do a get transaction
[ "do", "a", "get", "transaction" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L209-L211
train
206,753
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.post
def post(self, url): """ do a post request """ return requests.post(url, data=self.data, headers=self.config.HEADERS)
python
def post(self, url): """ do a post request """ return requests.post(url, data=self.data, headers=self.config.HEADERS)
[ "def", "post", "(", "self", ",", "url", ")", ":", "return", "requests", ".", "post", "(", "url", ",", "data", "=", "self", ".", "data", ",", "headers", "=", "self", ".", "config", ".", "HEADERS", ")" ]
do a post request
[ "do", "a", "post", "request" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L213-L215
train
206,754
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.checkout
def checkout(self, transparent=False, **kwargs): """ create a pagseguro checkout """ self.data['currency'] = self.config.CURRENCY self.build_checkout_params(**kwargs) if transparent: response = self.post(url=self.config.TRANSPARENT_CHECKOUT_URL) else: response = self.post(url=self.config.CHECKOUT_URL) return PagSeguroCheckoutResponse(response.content, config=self.config)
python
def checkout(self, transparent=False, **kwargs): """ create a pagseguro checkout """ self.data['currency'] = self.config.CURRENCY self.build_checkout_params(**kwargs) if transparent: response = self.post(url=self.config.TRANSPARENT_CHECKOUT_URL) else: response = self.post(url=self.config.CHECKOUT_URL) return PagSeguroCheckoutResponse(response.content, config=self.config)
[ "def", "checkout", "(", "self", ",", "transparent", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "data", "[", "'currency'", "]", "=", "self", ".", "config", ".", "CURRENCY", "self", ".", "build_checkout_params", "(", "*", "*", "kwargs"...
create a pagseguro checkout
[ "create", "a", "pagseguro", "checkout" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L217-L225
train
206,755
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.pre_approval_ask_payment
def pre_approval_ask_payment(self, **kwargs): """ ask form a subscribe payment """ self.build_pre_approval_payment_params(**kwargs) response = self.post(url=self.config.PRE_APPROVAL_PAYMENT_URL) return PagSeguroPreApprovalPayment(response.content, self.config)
python
def pre_approval_ask_payment(self, **kwargs): """ ask form a subscribe payment """ self.build_pre_approval_payment_params(**kwargs) response = self.post(url=self.config.PRE_APPROVAL_PAYMENT_URL) return PagSeguroPreApprovalPayment(response.content, self.config)
[ "def", "pre_approval_ask_payment", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "build_pre_approval_payment_params", "(", "*", "*", "kwargs", ")", "response", "=", "self", ".", "post", "(", "url", "=", "self", ".", "config", ".", "PRE_APPRO...
ask form a subscribe payment
[ "ask", "form", "a", "subscribe", "payment" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L244-L248
train
206,756
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.pre_approval_cancel
def pre_approval_cancel(self, code): """ cancel a subscribe """ response = self.get(url=self.config.PRE_APPROVAL_CANCEL_URL % code) return PagSeguroPreApprovalCancel(response.content, self.config)
python
def pre_approval_cancel(self, code): """ cancel a subscribe """ response = self.get(url=self.config.PRE_APPROVAL_CANCEL_URL % code) return PagSeguroPreApprovalCancel(response.content, self.config)
[ "def", "pre_approval_cancel", "(", "self", ",", "code", ")", ":", "response", "=", "self", ".", "get", "(", "url", "=", "self", ".", "config", ".", "PRE_APPROVAL_CANCEL_URL", "%", "code", ")", "return", "PagSeguroPreApprovalCancel", "(", "response", ".", "co...
cancel a subscribe
[ "cancel", "a", "subscribe" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L250-L253
train
206,757
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.check_transaction
def check_transaction(self, code): """ check a transaction by its code """ response = self.get(url=self.config.TRANSACTION_URL % code) return PagSeguroNotificationResponse(response.content, self.config)
python
def check_transaction(self, code): """ check a transaction by its code """ response = self.get(url=self.config.TRANSACTION_URL % code) return PagSeguroNotificationResponse(response.content, self.config)
[ "def", "check_transaction", "(", "self", ",", "code", ")", ":", "response", "=", "self", ".", "get", "(", "url", "=", "self", ".", "config", ".", "TRANSACTION_URL", "%", "code", ")", "return", "PagSeguroNotificationResponse", "(", "response", ".", "content",...
check a transaction by its code
[ "check", "a", "transaction", "by", "its", "code" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L255-L258
train
206,758
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.query_transactions
def query_transactions(self, initial_date, final_date, page=None, max_results=None): """ query transaction by date range """ last_page = False results = [] while last_page is False: search_result = self._consume_query_transactions( initial_date, final_date, page, max_results) results.extend(search_result.transactions) if search_result.current_page is None or \ search_result.total_pages is None or \ search_result.current_page == search_result.total_pages: last_page = True else: page = search_result.current_page + 1 return results
python
def query_transactions(self, initial_date, final_date, page=None, max_results=None): """ query transaction by date range """ last_page = False results = [] while last_page is False: search_result = self._consume_query_transactions( initial_date, final_date, page, max_results) results.extend(search_result.transactions) if search_result.current_page is None or \ search_result.total_pages is None or \ search_result.current_page == search_result.total_pages: last_page = True else: page = search_result.current_page + 1 return results
[ "def", "query_transactions", "(", "self", ",", "initial_date", ",", "final_date", ",", "page", "=", "None", ",", "max_results", "=", "None", ")", ":", "last_page", "=", "False", "results", "=", "[", "]", "while", "last_page", "is", "False", ":", "search_re...
query transaction by date range
[ "query", "transaction", "by", "date", "range" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L260-L277
train
206,759
rochacbruno/python-pagseguro
pagseguro/__init__.py
PagSeguro.query_pre_approvals
def query_pre_approvals(self, initial_date, final_date, page=None, max_results=None): """ query pre-approvals by date range """ last_page = False results = [] while last_page is False: search_result = self._consume_query_pre_approvals( initial_date, final_date, page, max_results) results.extend(search_result.pre_approvals) if search_result.current_page is None or \ search_result.total_pages is None or \ search_result.current_page == search_result.total_pages: last_page = True else: page = search_result.current_page + 1 return results
python
def query_pre_approvals(self, initial_date, final_date, page=None, max_results=None): """ query pre-approvals by date range """ last_page = False results = [] while last_page is False: search_result = self._consume_query_pre_approvals( initial_date, final_date, page, max_results) results.extend(search_result.pre_approvals) if search_result.current_page is None or \ search_result.total_pages is None or \ search_result.current_page == search_result.total_pages: last_page = True else: page = search_result.current_page + 1 return results
[ "def", "query_pre_approvals", "(", "self", ",", "initial_date", ",", "final_date", ",", "page", "=", "None", ",", "max_results", "=", "None", ")", ":", "last_page", "=", "False", "results", "=", "[", "]", "while", "last_page", "is", "False", ":", "search_r...
query pre-approvals by date range
[ "query", "pre", "-", "approvals", "by", "date", "range" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L293-L309
train
206,760
rochacbruno/python-pagseguro
examples/flask/flask_seguro/controllers/main/__init__.py
add_to_cart
def add_to_cart(item_id): """ Cart with Product """ cart = Cart(session['cart']) if cart.change_item(item_id, 'add'): session['cart'] = cart.to_dict() return list_products()
python
def add_to_cart(item_id): """ Cart with Product """ cart = Cart(session['cart']) if cart.change_item(item_id, 'add'): session['cart'] = cart.to_dict() return list_products()
[ "def", "add_to_cart", "(", "item_id", ")", ":", "cart", "=", "Cart", "(", "session", "[", "'cart'", "]", ")", "if", "cart", ".", "change_item", "(", "item_id", ",", "'add'", ")", ":", "session", "[", "'cart'", "]", "=", "cart", ".", "to_dict", "(", ...
Cart with Product
[ "Cart", "with", "Product" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/examples/flask/flask_seguro/controllers/main/__init__.py#L44-L49
train
206,761
rochacbruno/python-pagseguro
examples/flask/flask_seguro/cart.py
Cart.to_dict
def to_dict(self): """ Attribute values to dict """ return { "total": self.total, "subtotal": self.subtotal, "items": self.items, "extra_amount": self.extra_amount }
python
def to_dict(self): """ Attribute values to dict """ return { "total": self.total, "subtotal": self.subtotal, "items": self.items, "extra_amount": self.extra_amount }
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"total\"", ":", "self", ".", "total", ",", "\"subtotal\"", ":", "self", ".", "subtotal", ",", "\"items\"", ":", "self", ".", "items", ",", "\"extra_amount\"", ":", "self", ".", "extra_amount", "}"...
Attribute values to dict
[ "Attribute", "values", "to", "dict" ]
18a9ca3301783cb323e838574b59f9ddffa9a593
https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/examples/flask/flask_seguro/cart.py#L24-L32
train
206,762
neo4j-contrib/neomodel
neomodel/util.py
Database.set_connection
def set_connection(self, url): """ Sets the connection URL to the address a Neo4j server is set up at """ u = urlparse(url) if u.netloc.find('@') > -1 and (u.scheme == 'bolt' or u.scheme == 'bolt+routing'): credentials, hostname = u.netloc.rsplit('@', 1) username, password, = credentials.split(':') else: raise ValueError("Expecting url format: bolt://user:password@localhost:7687" " got {0}".format(url)) self.driver = GraphDatabase.driver(u.scheme + '://' + hostname, auth=basic_auth(username, password), encrypted=config.ENCRYPTED_CONNECTION, max_pool_size=config.MAX_POOL_SIZE) self.url = url self._pid = os.getpid() self._active_transaction = None
python
def set_connection(self, url): """ Sets the connection URL to the address a Neo4j server is set up at """ u = urlparse(url) if u.netloc.find('@') > -1 and (u.scheme == 'bolt' or u.scheme == 'bolt+routing'): credentials, hostname = u.netloc.rsplit('@', 1) username, password, = credentials.split(':') else: raise ValueError("Expecting url format: bolt://user:password@localhost:7687" " got {0}".format(url)) self.driver = GraphDatabase.driver(u.scheme + '://' + hostname, auth=basic_auth(username, password), encrypted=config.ENCRYPTED_CONNECTION, max_pool_size=config.MAX_POOL_SIZE) self.url = url self._pid = os.getpid() self._active_transaction = None
[ "def", "set_connection", "(", "self", ",", "url", ")", ":", "u", "=", "urlparse", "(", "url", ")", "if", "u", ".", "netloc", ".", "find", "(", "'@'", ")", ">", "-", "1", "and", "(", "u", ".", "scheme", "==", "'bolt'", "or", "u", ".", "scheme", ...
Sets the connection URL to the address a Neo4j server is set up at
[ "Sets", "the", "connection", "URL", "to", "the", "address", "a", "Neo4j", "server", "is", "set", "up", "at" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/util.py#L80-L99
train
206,763
neo4j-contrib/neomodel
neomodel/util.py
Database.begin
def begin(self, access_mode=None): """ Begins a new transaction, raises SystemError exception if a transaction is in progress """ if self._active_transaction: raise SystemError("Transaction in progress") self._active_transaction = self.driver.session(access_mode=access_mode).begin_transaction()
python
def begin(self, access_mode=None): """ Begins a new transaction, raises SystemError exception if a transaction is in progress """ if self._active_transaction: raise SystemError("Transaction in progress") self._active_transaction = self.driver.session(access_mode=access_mode).begin_transaction()
[ "def", "begin", "(", "self", ",", "access_mode", "=", "None", ")", ":", "if", "self", ".", "_active_transaction", ":", "raise", "SystemError", "(", "\"Transaction in progress\"", ")", "self", ".", "_active_transaction", "=", "self", ".", "driver", ".", "sessio...
Begins a new transaction, raises SystemError exception if a transaction is in progress
[ "Begins", "a", "new", "transaction", "raises", "SystemError", "exception", "if", "a", "transaction", "is", "in", "progress" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/util.py#L117-L123
train
206,764
neo4j-contrib/neomodel
neomodel/util.py
Database._object_resolution
def _object_resolution(self, result_list): """ Performs in place automatic object resolution on a set of results returned by cypher_query. The function operates recursively in order to be able to resolve Nodes within nested list structures. Not meant to be called directly, used primarily by cypher_query. :param result_list: A list of results as returned by cypher_query. :type list: :return: A list of instantiated objects. """ # Object resolution occurs in-place for a_result_item in enumerate(result_list): for a_result_attribute in enumerate(a_result_item[1]): try: # Primitive types should remain primitive types, # Nodes to be resolved to native objects resolved_object = a_result_attribute[1] if type(a_result_attribute[1]) is Node: resolved_object = self._NODE_CLASS_REGISTRY[frozenset(a_result_attribute[1].labels)].inflate( a_result_attribute[1]) if type(a_result_attribute[1]) is list: resolved_object = self._object_resolution([a_result_attribute[1]]) result_list[a_result_item[0]][a_result_attribute[0]] = resolved_object except KeyError: # Not being able to match the label set of a node with a known object results # in a KeyError in the internal dictionary used for resolution. If it is impossible # to match, then raise an exception with more details about the error. raise ModelDefinitionMismatch(a_result_attribute[1], self._NODE_CLASS_REGISTRY) return result_list
python
def _object_resolution(self, result_list): """ Performs in place automatic object resolution on a set of results returned by cypher_query. The function operates recursively in order to be able to resolve Nodes within nested list structures. Not meant to be called directly, used primarily by cypher_query. :param result_list: A list of results as returned by cypher_query. :type list: :return: A list of instantiated objects. """ # Object resolution occurs in-place for a_result_item in enumerate(result_list): for a_result_attribute in enumerate(a_result_item[1]): try: # Primitive types should remain primitive types, # Nodes to be resolved to native objects resolved_object = a_result_attribute[1] if type(a_result_attribute[1]) is Node: resolved_object = self._NODE_CLASS_REGISTRY[frozenset(a_result_attribute[1].labels)].inflate( a_result_attribute[1]) if type(a_result_attribute[1]) is list: resolved_object = self._object_resolution([a_result_attribute[1]]) result_list[a_result_item[0]][a_result_attribute[0]] = resolved_object except KeyError: # Not being able to match the label set of a node with a known object results # in a KeyError in the internal dictionary used for resolution. If it is impossible # to match, then raise an exception with more details about the error. raise ModelDefinitionMismatch(a_result_attribute[1], self._NODE_CLASS_REGISTRY) return result_list
[ "def", "_object_resolution", "(", "self", ",", "result_list", ")", ":", "# Object resolution occurs in-place", "for", "a_result_item", "in", "enumerate", "(", "result_list", ")", ":", "for", "a_result_attribute", "in", "enumerate", "(", "a_result_item", "[", "1", "]...
Performs in place automatic object resolution on a set of results returned by cypher_query. The function operates recursively in order to be able to resolve Nodes within nested list structures. Not meant to be called directly, used primarily by cypher_query. :param result_list: A list of results as returned by cypher_query. :type list: :return: A list of instantiated objects.
[ "Performs", "in", "place", "automatic", "object", "resolution", "on", "a", "set", "of", "results", "returned", "by", "cypher_query", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/util.py#L142-L180
train
206,765
neo4j-contrib/neomodel
neomodel/match.py
install_traversals
def install_traversals(cls, node_set): """ For a StructuredNode class install Traversal objects for each relationship definition on a NodeSet instance """ rels = cls.defined_properties(rels=True, aliases=False, properties=False) for key, value in rels.items(): if hasattr(node_set, key): raise ValueError("Can't install traversal '{0}' exists on NodeSet".format(key)) rel = getattr(cls, key) rel._lookup_node_class() traversal = Traversal(source=node_set, name=key, definition=rel.definition) setattr(node_set, key, traversal)
python
def install_traversals(cls, node_set): """ For a StructuredNode class install Traversal objects for each relationship definition on a NodeSet instance """ rels = cls.defined_properties(rels=True, aliases=False, properties=False) for key, value in rels.items(): if hasattr(node_set, key): raise ValueError("Can't install traversal '{0}' exists on NodeSet".format(key)) rel = getattr(cls, key) rel._lookup_node_class() traversal = Traversal(source=node_set, name=key, definition=rel.definition) setattr(node_set, key, traversal)
[ "def", "install_traversals", "(", "cls", ",", "node_set", ")", ":", "rels", "=", "cls", ".", "defined_properties", "(", "rels", "=", "True", ",", "aliases", "=", "False", ",", "properties", "=", "False", ")", "for", "key", ",", "value", "in", "rels", "...
For a StructuredNode class install Traversal objects for each relationship definition on a NodeSet instance
[ "For", "a", "StructuredNode", "class", "install", "Traversal", "objects", "for", "each", "relationship", "definition", "on", "a", "NodeSet", "instance" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L111-L126
train
206,766
neo4j-contrib/neomodel
neomodel/match.py
process_filter_args
def process_filter_args(cls, kwargs): """ loop through properties in filter parameters check they match class definition deflate them and convert into something easy to generate cypher from """ output = {} for key, value in kwargs.items(): if '__' in key: prop, operator = key.rsplit('__') operator = OPERATOR_TABLE[operator] else: prop = key operator = '=' if prop not in cls.defined_properties(rels=False): raise ValueError("No such property {0} on {1}".format(prop, cls.__name__)) property_obj = getattr(cls, prop) if isinstance(property_obj, AliasProperty): prop = property_obj.aliased_to() deflated_value = getattr(cls, prop).deflate(value) else: # handle special operators if operator == _SPECIAL_OPERATOR_IN: if not isinstance(value, tuple) and not isinstance(value, list): raise ValueError('Value must be a tuple or list for IN operation {0}={1}'.format(key, value)) deflated_value = [property_obj.deflate(v) for v in value] elif operator == _SPECIAL_OPERATOR_ISNULL: if not isinstance(value, bool): raise ValueError('Value must be a bool for isnull operation on {0}'.format(key)) operator = 'IS NULL' if value else 'IS NOT NULL' deflated_value = None elif operator in _REGEX_OPERATOR_TABLE.values(): deflated_value = property_obj.deflate(value) if not isinstance(deflated_value, basestring): raise ValueError('Must be a string value for {0}'.format(key)) if operator in _STRING_REGEX_OPERATOR_TABLE.values(): deflated_value = re.escape(deflated_value) deflated_value = operator.format(deflated_value) operator = _SPECIAL_OPERATOR_REGEX else: deflated_value = property_obj.deflate(value) # map property to correct property name in the database db_property = cls.defined_properties(rels=False)[prop].db_property or prop output[db_property] = (operator, deflated_value) return output
python
def process_filter_args(cls, kwargs): """ loop through properties in filter parameters check they match class definition deflate them and convert into something easy to generate cypher from """ output = {} for key, value in kwargs.items(): if '__' in key: prop, operator = key.rsplit('__') operator = OPERATOR_TABLE[operator] else: prop = key operator = '=' if prop not in cls.defined_properties(rels=False): raise ValueError("No such property {0} on {1}".format(prop, cls.__name__)) property_obj = getattr(cls, prop) if isinstance(property_obj, AliasProperty): prop = property_obj.aliased_to() deflated_value = getattr(cls, prop).deflate(value) else: # handle special operators if operator == _SPECIAL_OPERATOR_IN: if not isinstance(value, tuple) and not isinstance(value, list): raise ValueError('Value must be a tuple or list for IN operation {0}={1}'.format(key, value)) deflated_value = [property_obj.deflate(v) for v in value] elif operator == _SPECIAL_OPERATOR_ISNULL: if not isinstance(value, bool): raise ValueError('Value must be a bool for isnull operation on {0}'.format(key)) operator = 'IS NULL' if value else 'IS NOT NULL' deflated_value = None elif operator in _REGEX_OPERATOR_TABLE.values(): deflated_value = property_obj.deflate(value) if not isinstance(deflated_value, basestring): raise ValueError('Must be a string value for {0}'.format(key)) if operator in _STRING_REGEX_OPERATOR_TABLE.values(): deflated_value = re.escape(deflated_value) deflated_value = operator.format(deflated_value) operator = _SPECIAL_OPERATOR_REGEX else: deflated_value = property_obj.deflate(value) # map property to correct property name in the database db_property = cls.defined_properties(rels=False)[prop].db_property or prop output[db_property] = (operator, deflated_value) return output
[ "def", "process_filter_args", "(", "cls", ",", "kwargs", ")", ":", "output", "=", "{", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "'__'", "in", "key", ":", "prop", ",", "operator", "=", "key", ".", "rsplit",...
loop through properties in filter parameters check they match class definition deflate them and convert into something easy to generate cypher from
[ "loop", "through", "properties", "in", "filter", "parameters", "check", "they", "match", "class", "definition", "deflate", "them", "and", "convert", "into", "something", "easy", "to", "generate", "cypher", "from" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L129-L179
train
206,767
neo4j-contrib/neomodel
neomodel/match.py
process_has_args
def process_has_args(cls, kwargs): """ loop through has parameters check they correspond to class rels defined """ rel_definitions = cls.defined_properties(properties=False, rels=True, aliases=False) match, dont_match = {}, {} for key, value in kwargs.items(): if key not in rel_definitions: raise ValueError("No such relation {0} defined on a {1}".format(key, cls.__name__)) rhs_ident = key rel_definitions[key]._lookup_node_class() if value is True: match[rhs_ident] = rel_definitions[key].definition elif value is False: dont_match[rhs_ident] = rel_definitions[key].definition elif isinstance(value, NodeSet): raise NotImplementedError("Not implemented yet") else: raise ValueError("Expecting True / False / NodeSet got: " + repr(value)) return match, dont_match
python
def process_has_args(cls, kwargs): """ loop through has parameters check they correspond to class rels defined """ rel_definitions = cls.defined_properties(properties=False, rels=True, aliases=False) match, dont_match = {}, {} for key, value in kwargs.items(): if key not in rel_definitions: raise ValueError("No such relation {0} defined on a {1}".format(key, cls.__name__)) rhs_ident = key rel_definitions[key]._lookup_node_class() if value is True: match[rhs_ident] = rel_definitions[key].definition elif value is False: dont_match[rhs_ident] = rel_definitions[key].definition elif isinstance(value, NodeSet): raise NotImplementedError("Not implemented yet") else: raise ValueError("Expecting True / False / NodeSet got: " + repr(value)) return match, dont_match
[ "def", "process_has_args", "(", "cls", ",", "kwargs", ")", ":", "rel_definitions", "=", "cls", ".", "defined_properties", "(", "properties", "=", "False", ",", "rels", "=", "True", ",", "aliases", "=", "False", ")", "match", ",", "dont_match", "=", "{", ...
loop through has parameters check they correspond to class rels defined
[ "loop", "through", "has", "parameters", "check", "they", "correspond", "to", "class", "rels", "defined" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L182-L207
train
206,768
neo4j-contrib/neomodel
neomodel/match.py
QueryBuilder.build_traversal
def build_traversal(self, traversal): """ traverse a relationship from a node to a set of nodes """ # build source rhs_label = ':' + traversal.target_class.__label__ # build source lhs_ident = self.build_source(traversal.source) rhs_ident = traversal.name + rhs_label self._ast['return'] = traversal.name self._ast['result_class'] = traversal.target_class rel_ident = self.create_ident() stmt = _rel_helper(lhs=lhs_ident, rhs=rhs_ident, ident=rel_ident, **traversal.definition) self._ast['match'].append(stmt) if traversal.filters: self.build_where_stmt(rel_ident, traversal.filters) return traversal.name
python
def build_traversal(self, traversal): """ traverse a relationship from a node to a set of nodes """ # build source rhs_label = ':' + traversal.target_class.__label__ # build source lhs_ident = self.build_source(traversal.source) rhs_ident = traversal.name + rhs_label self._ast['return'] = traversal.name self._ast['result_class'] = traversal.target_class rel_ident = self.create_ident() stmt = _rel_helper(lhs=lhs_ident, rhs=rhs_ident, ident=rel_ident, **traversal.definition) self._ast['match'].append(stmt) if traversal.filters: self.build_where_stmt(rel_ident, traversal.filters) return traversal.name
[ "def", "build_traversal", "(", "self", ",", "traversal", ")", ":", "# build source", "rhs_label", "=", "':'", "+", "traversal", ".", "target_class", ".", "__label__", "# build source", "lhs_ident", "=", "self", ".", "build_source", "(", "traversal", ".", "source...
traverse a relationship from a node to a set of nodes
[ "traverse", "a", "relationship", "from", "a", "node", "to", "a", "set", "of", "nodes" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L263-L283
train
206,769
neo4j-contrib/neomodel
neomodel/match.py
QueryBuilder.build_label
def build_label(self, ident, cls): """ match nodes by a label """ ident_w_label = ident + ':' + cls.__label__ self._ast['match'].append('({0})'.format(ident_w_label)) self._ast['return'] = ident self._ast['result_class'] = cls return ident
python
def build_label(self, ident, cls): """ match nodes by a label """ ident_w_label = ident + ':' + cls.__label__ self._ast['match'].append('({0})'.format(ident_w_label)) self._ast['return'] = ident self._ast['result_class'] = cls return ident
[ "def", "build_label", "(", "self", ",", "ident", ",", "cls", ")", ":", "ident_w_label", "=", "ident", "+", "':'", "+", "cls", ".", "__label__", "self", ".", "_ast", "[", "'match'", "]", ".", "append", "(", "'({0})'", ".", "format", "(", "ident_w_label"...
match nodes by a label
[ "match", "nodes", "by", "a", "label" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L299-L307
train
206,770
neo4j-contrib/neomodel
neomodel/match.py
QueryBuilder.build_where_stmt
def build_where_stmt(self, ident, filters, q_filters=None, source_class=None): """ construct a where statement from some filters """ if q_filters is not None: stmts = self._parse_q_filters(ident, q_filters, source_class) if stmts: self._ast['where'].append(stmts) else: stmts = [] for row in filters: negate = False # pre-process NOT cases as they are nested dicts if '__NOT__' in row and len(row) == 1: negate = True row = row['__NOT__'] for prop, op_and_val in row.items(): op, val = op_and_val if op in _UNARY_OPERATORS: # unary operators do not have a parameter statement = '{0} {1}.{2} {3}'.format('NOT' if negate else '', ident, prop, op) else: place_holder = self._register_place_holder(ident + '_' + prop) statement = '{0} {1}.{2} {3} {{{4}}}'.format('NOT' if negate else '', ident, prop, op, place_holder) self._query_params[place_holder] = val stmts.append(statement) self._ast['where'].append(' AND '.join(stmts))
python
def build_where_stmt(self, ident, filters, q_filters=None, source_class=None): """ construct a where statement from some filters """ if q_filters is not None: stmts = self._parse_q_filters(ident, q_filters, source_class) if stmts: self._ast['where'].append(stmts) else: stmts = [] for row in filters: negate = False # pre-process NOT cases as they are nested dicts if '__NOT__' in row and len(row) == 1: negate = True row = row['__NOT__'] for prop, op_and_val in row.items(): op, val = op_and_val if op in _UNARY_OPERATORS: # unary operators do not have a parameter statement = '{0} {1}.{2} {3}'.format('NOT' if negate else '', ident, prop, op) else: place_holder = self._register_place_holder(ident + '_' + prop) statement = '{0} {1}.{2} {3} {{{4}}}'.format('NOT' if negate else '', ident, prop, op, place_holder) self._query_params[place_holder] = val stmts.append(statement) self._ast['where'].append(' AND '.join(stmts))
[ "def", "build_where_stmt", "(", "self", ",", "ident", ",", "filters", ",", "q_filters", "=", "None", ",", "source_class", "=", "None", ")", ":", "if", "q_filters", "is", "not", "None", ":", "stmts", "=", "self", ".", "_parse_q_filters", "(", "ident", ","...
construct a where statement from some filters
[ "construct", "a", "where", "statement", "from", "some", "filters" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L364-L393
train
206,771
neo4j-contrib/neomodel
neomodel/match.py
NodeSet.first
def first(self, **kwargs): """ Retrieve the first node from the set matching supplied parameters :param kwargs: same syntax as `filter()` :return: node """ result = result = self._get(limit=1, **kwargs) if result: return result[0] else: raise self.source_class.DoesNotExist(repr(kwargs))
python
def first(self, **kwargs): """ Retrieve the first node from the set matching supplied parameters :param kwargs: same syntax as `filter()` :return: node """ result = result = self._get(limit=1, **kwargs) if result: return result[0] else: raise self.source_class.DoesNotExist(repr(kwargs))
[ "def", "first", "(", "self", ",", "*", "*", "kwargs", ")", ":", "result", "=", "result", "=", "self", ".", "_get", "(", "limit", "=", "1", ",", "*", "*", "kwargs", ")", "if", "result", ":", "return", "result", "[", "0", "]", "else", ":", "raise...
Retrieve the first node from the set matching supplied parameters :param kwargs: same syntax as `filter()` :return: node
[ "Retrieve", "the", "first", "node", "from", "the", "set", "matching", "supplied", "parameters" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L571-L582
train
206,772
neo4j-contrib/neomodel
neomodel/match.py
NodeSet.filter
def filter(self, *args, **kwargs): """ Apply filters to the existing nodes in the set. :param kwargs: filter parameters Filters mimic Django's syntax with the double '__' to separate field and operators. e.g `.filter(salary__gt=20000)` results in `salary > 20000`. The following operators are available: * 'lt': less than * 'gt': greater than * 'lte': less than or equal to * 'gte': greater than or equal to * 'ne': not equal to * 'in': matches one of list (or tuple) * 'isnull': is null * 'regex': matches supplied regex (neo4j regex format) * 'exact': exactly match string (just '=') * 'iexact': case insensitive match string * 'contains': contains string * 'icontains': case insensitive contains * 'startswith': string starts with * 'istartswith': case insensitive string starts with * 'endswith': string ends with * 'iendswith': case insensitive string ends with :return: self """ if args or kwargs: self.q_filters = Q(self.q_filters & Q(*args, **kwargs)) return self
python
def filter(self, *args, **kwargs): """ Apply filters to the existing nodes in the set. :param kwargs: filter parameters Filters mimic Django's syntax with the double '__' to separate field and operators. e.g `.filter(salary__gt=20000)` results in `salary > 20000`. The following operators are available: * 'lt': less than * 'gt': greater than * 'lte': less than or equal to * 'gte': greater than or equal to * 'ne': not equal to * 'in': matches one of list (or tuple) * 'isnull': is null * 'regex': matches supplied regex (neo4j regex format) * 'exact': exactly match string (just '=') * 'iexact': case insensitive match string * 'contains': contains string * 'icontains': case insensitive contains * 'startswith': string starts with * 'istartswith': case insensitive string starts with * 'endswith': string ends with * 'iendswith': case insensitive string ends with :return: self """ if args or kwargs: self.q_filters = Q(self.q_filters & Q(*args, **kwargs)) return self
[ "def", "filter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "or", "kwargs", ":", "self", ".", "q_filters", "=", "Q", "(", "self", ".", "q_filters", "&", "Q", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
Apply filters to the existing nodes in the set. :param kwargs: filter parameters Filters mimic Django's syntax with the double '__' to separate field and operators. e.g `.filter(salary__gt=20000)` results in `salary > 20000`. The following operators are available: * 'lt': less than * 'gt': greater than * 'lte': less than or equal to * 'gte': greater than or equal to * 'ne': not equal to * 'in': matches one of list (or tuple) * 'isnull': is null * 'regex': matches supplied regex (neo4j regex format) * 'exact': exactly match string (just '=') * 'iexact': case insensitive match string * 'contains': contains string * 'icontains': case insensitive contains * 'startswith': string starts with * 'istartswith': case insensitive string starts with * 'endswith': string ends with * 'iendswith': case insensitive string ends with :return: self
[ "Apply", "filters", "to", "the", "existing", "nodes", "in", "the", "set", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L596-L629
train
206,773
neo4j-contrib/neomodel
neomodel/match.py
NodeSet.exclude
def exclude(self, *args, **kwargs): """ Exclude nodes from the NodeSet via filters. :param kwargs: filter parameters see syntax for the filter method :return: self """ if args or kwargs: self.q_filters = Q(self.q_filters & ~Q(*args, **kwargs)) return self
python
def exclude(self, *args, **kwargs): """ Exclude nodes from the NodeSet via filters. :param kwargs: filter parameters see syntax for the filter method :return: self """ if args or kwargs: self.q_filters = Q(self.q_filters & ~Q(*args, **kwargs)) return self
[ "def", "exclude", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "or", "kwargs", ":", "self", ".", "q_filters", "=", "Q", "(", "self", ".", "q_filters", "&", "~", "Q", "(", "*", "args", ",", "*", "*", "kwargs", ...
Exclude nodes from the NodeSet via filters. :param kwargs: filter parameters see syntax for the filter method :return: self
[ "Exclude", "nodes", "from", "the", "NodeSet", "via", "filters", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L631-L640
train
206,774
neo4j-contrib/neomodel
neomodel/match.py
NodeSet.order_by
def order_by(self, *props): """ Order by properties. Prepend with minus to do descending. Pass None to remove ordering. """ should_remove = len(props) == 1 and props[0] is None if not hasattr(self, '_order_by') or should_remove: self._order_by = [] if should_remove: return self if '?' in props: self._order_by.append('?') else: for prop in props: prop = prop.strip() if prop.startswith('-'): prop = prop[1:] desc = True else: desc = False if prop not in self.source_class.defined_properties(rels=False): raise ValueError("No such property {0} on {1}".format( prop, self.source_class.__name__)) property_obj = getattr(self.source_class, prop) if isinstance(property_obj, AliasProperty): prop = property_obj.aliased_to() self._order_by.append(prop + (' DESC' if desc else '')) return self
python
def order_by(self, *props): """ Order by properties. Prepend with minus to do descending. Pass None to remove ordering. """ should_remove = len(props) == 1 and props[0] is None if not hasattr(self, '_order_by') or should_remove: self._order_by = [] if should_remove: return self if '?' in props: self._order_by.append('?') else: for prop in props: prop = prop.strip() if prop.startswith('-'): prop = prop[1:] desc = True else: desc = False if prop not in self.source_class.defined_properties(rels=False): raise ValueError("No such property {0} on {1}".format( prop, self.source_class.__name__)) property_obj = getattr(self.source_class, prop) if isinstance(property_obj, AliasProperty): prop = property_obj.aliased_to() self._order_by.append(prop + (' DESC' if desc else '')) return self
[ "def", "order_by", "(", "self", ",", "*", "props", ")", ":", "should_remove", "=", "len", "(", "props", ")", "==", "1", "and", "props", "[", "0", "]", "is", "None", "if", "not", "hasattr", "(", "self", ",", "'_order_by'", ")", "or", "should_remove", ...
Order by properties. Prepend with minus to do descending. Pass None to remove ordering.
[ "Order", "by", "properties", ".", "Prepend", "with", "minus", "to", "do", "descending", ".", "Pass", "None", "to", "remove", "ordering", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L648-L679
train
206,775
neo4j-contrib/neomodel
neomodel/match.py
Traversal.match
def match(self, **kwargs): """ Traverse relationships with properties matching the given parameters. e.g: `.match(price__lt=10)` :param kwargs: see `NodeSet.filter()` for syntax :return: self """ if kwargs: if self.definition.get('model') is None: raise ValueError("match() with filter only available on relationships with a model") output = process_filter_args(self.definition['model'], kwargs) if output: self.filters.append(output) return self
python
def match(self, **kwargs): """ Traverse relationships with properties matching the given parameters. e.g: `.match(price__lt=10)` :param kwargs: see `NodeSet.filter()` for syntax :return: self """ if kwargs: if self.definition.get('model') is None: raise ValueError("match() with filter only available on relationships with a model") output = process_filter_args(self.definition['model'], kwargs) if output: self.filters.append(output) return self
[ "def", "match", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "if", "self", ".", "definition", ".", "get", "(", "'model'", ")", "is", "None", ":", "raise", "ValueError", "(", "\"match() with filter only available on relationships with a ...
Traverse relationships with properties matching the given parameters. e.g: `.match(price__lt=10)` :param kwargs: see `NodeSet.filter()` for syntax :return: self
[ "Traverse", "relationships", "with", "properties", "matching", "the", "given", "parameters", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match.py#L730-L745
train
206,776
neo4j-contrib/neomodel
neomodel/contrib/spatial_properties.py
PointProperty.inflate
def inflate(self, value): """ Handles the marshalling from Neo4J POINT to NeomodelPoint :param value: Value returned from the database :type value: Neo4J POINT :return: NeomodelPoint """ if not isinstance(value,neo4j.types.spatial.Point): raise TypeError('Invalid datatype to inflate. Expected POINT datatype, received {}'.format(type(value))) try: value_point_crs = SRID_TO_CRS[value.srid] except KeyError: raise ValueError('Invalid SRID to inflate. ' 'Expected one of {}, received {}'.format(SRID_TO_CRS.keys(), value.srid)) if self._crs != value_point_crs: raise ValueError('Invalid CRS. ' 'Expected POINT defined over {}, received {}'.format(self._crs, value_point_crs)) # cartesian if value.srid == 7203: return NeomodelPoint(x=value.x, y=value.y) # cartesian-3d elif value.srid == 9157: return NeomodelPoint(x=value.x, y=value.y, z=value.z) # wgs-84 elif value.srid == 4326: return NeomodelPoint(longitude=value.longitude, latitude=value.latitude) # wgs-83-3d elif value.srid == 4979: return NeomodelPoint(longitude=value.longitude, latitude=value.latitude, height=value.height)
python
def inflate(self, value): """ Handles the marshalling from Neo4J POINT to NeomodelPoint :param value: Value returned from the database :type value: Neo4J POINT :return: NeomodelPoint """ if not isinstance(value,neo4j.types.spatial.Point): raise TypeError('Invalid datatype to inflate. Expected POINT datatype, received {}'.format(type(value))) try: value_point_crs = SRID_TO_CRS[value.srid] except KeyError: raise ValueError('Invalid SRID to inflate. ' 'Expected one of {}, received {}'.format(SRID_TO_CRS.keys(), value.srid)) if self._crs != value_point_crs: raise ValueError('Invalid CRS. ' 'Expected POINT defined over {}, received {}'.format(self._crs, value_point_crs)) # cartesian if value.srid == 7203: return NeomodelPoint(x=value.x, y=value.y) # cartesian-3d elif value.srid == 9157: return NeomodelPoint(x=value.x, y=value.y, z=value.z) # wgs-84 elif value.srid == 4326: return NeomodelPoint(longitude=value.longitude, latitude=value.latitude) # wgs-83-3d elif value.srid == 4979: return NeomodelPoint(longitude=value.longitude, latitude=value.latitude, height=value.height)
[ "def", "inflate", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "neo4j", ".", "types", ".", "spatial", ".", "Point", ")", ":", "raise", "TypeError", "(", "'Invalid datatype to inflate. Expected POINT datatype, received {}'", ...
Handles the marshalling from Neo4J POINT to NeomodelPoint :param value: Value returned from the database :type value: Neo4J POINT :return: NeomodelPoint
[ "Handles", "the", "marshalling", "from", "Neo4J", "POINT", "to", "NeomodelPoint" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/contrib/spatial_properties.py#L280-L311
train
206,777
neo4j-contrib/neomodel
neomodel/contrib/spatial_properties.py
PointProperty.deflate
def deflate(self, value): """ Handles the marshalling from NeomodelPoint to Neo4J POINT :param value: The point that was assigned as value to a property in the model :type value: NeomodelPoint :return: Neo4J POINT """ if not isinstance(value, NeomodelPoint): raise TypeError('Invalid datatype to deflate. Expected NeomodelPoint, received {}'.format(type(value))) if not value.crs == self._crs: raise ValueError('Invalid CRS. ' 'Expected NeomodelPoint defined over {}, ' 'received NeomodelPoint defined over {}'.format(self._crs, value.crs)) if value.crs == 'cartesian-3d': return neo4j.types.spatial.CartesianPoint((value.x, value.y, value.z)) elif value.crs == 'cartesian': return neo4j.types.spatial.CartesianPoint((value.x,value.y)) elif value.crs == 'wgs-84': return neo4j.types.spatial.WGS84Point((value.longitude, value.latitude)) elif value.crs == 'wgs-84-3d': return neo4j.types.spatial.WGS84Point((value.longitude, value.latitude, value.height))
python
def deflate(self, value): """ Handles the marshalling from NeomodelPoint to Neo4J POINT :param value: The point that was assigned as value to a property in the model :type value: NeomodelPoint :return: Neo4J POINT """ if not isinstance(value, NeomodelPoint): raise TypeError('Invalid datatype to deflate. Expected NeomodelPoint, received {}'.format(type(value))) if not value.crs == self._crs: raise ValueError('Invalid CRS. ' 'Expected NeomodelPoint defined over {}, ' 'received NeomodelPoint defined over {}'.format(self._crs, value.crs)) if value.crs == 'cartesian-3d': return neo4j.types.spatial.CartesianPoint((value.x, value.y, value.z)) elif value.crs == 'cartesian': return neo4j.types.spatial.CartesianPoint((value.x,value.y)) elif value.crs == 'wgs-84': return neo4j.types.spatial.WGS84Point((value.longitude, value.latitude)) elif value.crs == 'wgs-84-3d': return neo4j.types.spatial.WGS84Point((value.longitude, value.latitude, value.height))
[ "def", "deflate", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "NeomodelPoint", ")", ":", "raise", "TypeError", "(", "'Invalid datatype to deflate. Expected NeomodelPoint, received {}'", ".", "format", "(", "type", "(", "value...
Handles the marshalling from NeomodelPoint to Neo4J POINT :param value: The point that was assigned as value to a property in the model :type value: NeomodelPoint :return: Neo4J POINT
[ "Handles", "the", "marshalling", "from", "NeomodelPoint", "to", "Neo4J", "POINT" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/contrib/spatial_properties.py#L314-L337
train
206,778
neo4j-contrib/neomodel
neomodel/match_q.py
QBase.add
def add(self, data, conn_type, squash=True): """ Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. Return a node which can be used in place of data regardless if the node other got squashed or not. If `squash` is False the data is prepared and added as a child to this tree without further logic. Args: conn_type (str, optional ["AND", "OR"]): connection method """ if data in self.children: return data if not squash: self.children.append(data) return data if self.connector == conn_type: # We can reuse self.children to append or squash the node other. if (isinstance(data, QBase) and not data.negated and (data.connector == conn_type or len(data) == 1)): # We can squash the other node's children directly into this # node. We are just doing (AB)(CD) == (ABCD) here, with the # addition that if the length of the other node is 1 the # connector doesn't matter. However, for the len(self) == 1 # case we don't want to do the squashing, as it would alter # self.connector. self.children.extend(data.children) return self else: # We could use perhaps additional logic here to see if some # children could be used for pushdown here. self.children.append(data) return data else: obj = self._new_instance(self.children, self.connector, self.negated) self.connector = conn_type self.children = [obj, data] return data
python
def add(self, data, conn_type, squash=True): """ Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. Return a node which can be used in place of data regardless if the node other got squashed or not. If `squash` is False the data is prepared and added as a child to this tree without further logic. Args: conn_type (str, optional ["AND", "OR"]): connection method """ if data in self.children: return data if not squash: self.children.append(data) return data if self.connector == conn_type: # We can reuse self.children to append or squash the node other. if (isinstance(data, QBase) and not data.negated and (data.connector == conn_type or len(data) == 1)): # We can squash the other node's children directly into this # node. We are just doing (AB)(CD) == (ABCD) here, with the # addition that if the length of the other node is 1 the # connector doesn't matter. However, for the len(self) == 1 # case we don't want to do the squashing, as it would alter # self.connector. self.children.extend(data.children) return self else: # We could use perhaps additional logic here to see if some # children could be used for pushdown here. self.children.append(data) return data else: obj = self._new_instance(self.children, self.connector, self.negated) self.connector = conn_type self.children = [obj, data] return data
[ "def", "add", "(", "self", ",", "data", ",", "conn_type", ",", "squash", "=", "True", ")", ":", "if", "data", "in", "self", ".", "children", ":", "return", "data", "if", "not", "squash", ":", "self", ".", "children", ".", "append", "(", "data", ")"...
Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. Return a node which can be used in place of data regardless if the node other got squashed or not. If `squash` is False the data is prepared and added as a child to this tree without further logic. Args: conn_type (str, optional ["AND", "OR"]): connection method
[ "Combine", "this", "tree", "and", "the", "data", "represented", "by", "data", "using", "the", "connector", "conn_type", ".", "The", "combine", "is", "done", "by", "squashing", "the", "node", "other", "away", "if", "possible", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/match_q.py#L105-L150
train
206,779
neo4j-contrib/neomodel
neomodel/relationship_manager.py
RelationshipManager._check_node
def _check_node(self, obj): """check for valid node i.e correct class and is saved""" if not issubclass(type(obj), self.definition['node_class']): raise ValueError("Expected node of class " + self.definition['node_class'].__name__) if not hasattr(obj, 'id'): raise ValueError("Can't perform operation on unsaved node " + repr(obj))
python
def _check_node(self, obj): """check for valid node i.e correct class and is saved""" if not issubclass(type(obj), self.definition['node_class']): raise ValueError("Expected node of class " + self.definition['node_class'].__name__) if not hasattr(obj, 'id'): raise ValueError("Can't perform operation on unsaved node " + repr(obj))
[ "def", "_check_node", "(", "self", ",", "obj", ")", ":", "if", "not", "issubclass", "(", "type", "(", "obj", ")", ",", "self", ".", "definition", "[", "'node_class'", "]", ")", ":", "raise", "ValueError", "(", "\"Expected node of class \"", "+", "self", ...
check for valid node i.e correct class and is saved
[ "check", "for", "valid", "node", "i", ".", "e", "correct", "class", "and", "is", "saved" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship_manager.py#L51-L56
train
206,780
neo4j-contrib/neomodel
neomodel/relationship_manager.py
RelationshipManager.replace
def replace(self, node, properties=None): """ Disconnect all existing nodes and connect the supplied node :param node: :param properties: for the new relationship :type: dict :return: """ self.disconnect_all() self.connect(node, properties)
python
def replace(self, node, properties=None): """ Disconnect all existing nodes and connect the supplied node :param node: :param properties: for the new relationship :type: dict :return: """ self.disconnect_all() self.connect(node, properties)
[ "def", "replace", "(", "self", ",", "node", ",", "properties", "=", "None", ")", ":", "self", ".", "disconnect_all", "(", ")", "self", ".", "connect", "(", "node", ",", "properties", ")" ]
Disconnect all existing nodes and connect the supplied node :param node: :param properties: for the new relationship :type: dict :return:
[ "Disconnect", "all", "existing", "nodes", "and", "connect", "the", "supplied", "node" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship_manager.py#L111-L121
train
206,781
neo4j-contrib/neomodel
neomodel/relationship_manager.py
RelationshipManager.relationship
def relationship(self, node): """ Retrieve the relationship object for this first relationship between self and node. :param node: :return: StructuredRel """ self._check_node(node) my_rel = _rel_helper(lhs='us', rhs='them', ident='r', **self.definition) q = "MATCH " + my_rel + " WHERE id(them)={them} and id(us)={self} RETURN r LIMIT 1" rels = self.source.cypher(q, {'them': node.id})[0] if not rels: return rel_model = self.definition.get('model') or StructuredRel return self._set_start_end_cls(rel_model.inflate(rels[0][0]), node)
python
def relationship(self, node): """ Retrieve the relationship object for this first relationship between self and node. :param node: :return: StructuredRel """ self._check_node(node) my_rel = _rel_helper(lhs='us', rhs='them', ident='r', **self.definition) q = "MATCH " + my_rel + " WHERE id(them)={them} and id(us)={self} RETURN r LIMIT 1" rels = self.source.cypher(q, {'them': node.id})[0] if not rels: return rel_model = self.definition.get('model') or StructuredRel return self._set_start_end_cls(rel_model.inflate(rels[0][0]), node)
[ "def", "relationship", "(", "self", ",", "node", ")", ":", "self", ".", "_check_node", "(", "node", ")", "my_rel", "=", "_rel_helper", "(", "lhs", "=", "'us'", ",", "rhs", "=", "'them'", ",", "ident", "=", "'r'", ",", "*", "*", "self", ".", "defini...
Retrieve the relationship object for this first relationship between self and node. :param node: :return: StructuredRel
[ "Retrieve", "the", "relationship", "object", "for", "this", "first", "relationship", "between", "self", "and", "node", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship_manager.py#L124-L140
train
206,782
neo4j-contrib/neomodel
neomodel/relationship_manager.py
RelationshipManager.reconnect
def reconnect(self, old_node, new_node): """ Disconnect old_node and connect new_node copying over any properties on the original relationship. Useful for preventing cardinality violations :param old_node: :param new_node: :return: None """ self._check_node(old_node) self._check_node(new_node) if old_node.id == new_node.id: return old_rel = _rel_helper(lhs='us', rhs='old', ident='r', **self.definition) # get list of properties on the existing rel result, meta = self.source.cypher( "MATCH (us), (old) WHERE id(us)={self} and id(old)={old} " "MATCH " + old_rel + " RETURN r", {'old': old_node.id}) if result: node_properties = _get_node_properties(result[0][0]) existing_properties = node_properties.keys() else: raise NotConnected('reconnect', self.source, old_node) # remove old relationship and create new one new_rel = _rel_helper(lhs='us', rhs='new', ident='r2', **self.definition) q = "MATCH (us), (old), (new) " \ "WHERE id(us)={self} and id(old)={old} and id(new)={new} " \ "MATCH " + old_rel q += " CREATE UNIQUE" + new_rel # copy over properties if we have for p in existing_properties: q += " SET r2.{0} = r.{1}".format(p, p) q += " WITH r DELETE r" self.source.cypher(q, {'old': old_node.id, 'new': new_node.id})
python
def reconnect(self, old_node, new_node): """ Disconnect old_node and connect new_node copying over any properties on the original relationship. Useful for preventing cardinality violations :param old_node: :param new_node: :return: None """ self._check_node(old_node) self._check_node(new_node) if old_node.id == new_node.id: return old_rel = _rel_helper(lhs='us', rhs='old', ident='r', **self.definition) # get list of properties on the existing rel result, meta = self.source.cypher( "MATCH (us), (old) WHERE id(us)={self} and id(old)={old} " "MATCH " + old_rel + " RETURN r", {'old': old_node.id}) if result: node_properties = _get_node_properties(result[0][0]) existing_properties = node_properties.keys() else: raise NotConnected('reconnect', self.source, old_node) # remove old relationship and create new one new_rel = _rel_helper(lhs='us', rhs='new', ident='r2', **self.definition) q = "MATCH (us), (old), (new) " \ "WHERE id(us)={self} and id(old)={old} and id(new)={new} " \ "MATCH " + old_rel q += " CREATE UNIQUE" + new_rel # copy over properties if we have for p in existing_properties: q += " SET r2.{0} = r.{1}".format(p, p) q += " WITH r DELETE r" self.source.cypher(q, {'old': old_node.id, 'new': new_node.id})
[ "def", "reconnect", "(", "self", ",", "old_node", ",", "new_node", ")", ":", "self", ".", "_check_node", "(", "old_node", ")", "self", ".", "_check_node", "(", "new_node", ")", "if", "old_node", ".", "id", "==", "new_node", ".", "id", ":", "return", "o...
Disconnect old_node and connect new_node copying over any properties on the original relationship. Useful for preventing cardinality violations :param old_node: :param new_node: :return: None
[ "Disconnect", "old_node", "and", "connect", "new_node", "copying", "over", "any", "properties", "on", "the", "original", "relationship", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship_manager.py#L171-L210
train
206,783
neo4j-contrib/neomodel
neomodel/relationship_manager.py
RelationshipManager.disconnect
def disconnect(self, node): """ Disconnect a node :param node: :return: """ rel = _rel_helper(lhs='a', rhs='b', ident='r', **self.definition) q = "MATCH (a), (b) WHERE id(a)={self} and id(b)={them} " \ "MATCH " + rel + " DELETE r" self.source.cypher(q, {'them': node.id})
python
def disconnect(self, node): """ Disconnect a node :param node: :return: """ rel = _rel_helper(lhs='a', rhs='b', ident='r', **self.definition) q = "MATCH (a), (b) WHERE id(a)={self} and id(b)={them} " \ "MATCH " + rel + " DELETE r" self.source.cypher(q, {'them': node.id})
[ "def", "disconnect", "(", "self", ",", "node", ")", ":", "rel", "=", "_rel_helper", "(", "lhs", "=", "'a'", ",", "rhs", "=", "'b'", ",", "ident", "=", "'r'", ",", "*", "*", "self", ".", "definition", ")", "q", "=", "\"MATCH (a), (b) WHERE id(a)={self} ...
Disconnect a node :param node: :return:
[ "Disconnect", "a", "node" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship_manager.py#L213-L223
train
206,784
neo4j-contrib/neomodel
neomodel/relationship_manager.py
RelationshipManager.disconnect_all
def disconnect_all(self): """ Disconnect all nodes :return: """ rhs = 'b:' + self.definition['node_class'].__label__ rel = _rel_helper(lhs='a', rhs=rhs, ident='r', **self.definition) q = 'MATCH (a) WHERE id(a)={self} MATCH ' + rel + ' DELETE r' self.source.cypher(q)
python
def disconnect_all(self): """ Disconnect all nodes :return: """ rhs = 'b:' + self.definition['node_class'].__label__ rel = _rel_helper(lhs='a', rhs=rhs, ident='r', **self.definition) q = 'MATCH (a) WHERE id(a)={self} MATCH ' + rel + ' DELETE r' self.source.cypher(q)
[ "def", "disconnect_all", "(", "self", ")", ":", "rhs", "=", "'b:'", "+", "self", ".", "definition", "[", "'node_class'", "]", ".", "__label__", "rel", "=", "_rel_helper", "(", "lhs", "=", "'a'", ",", "rhs", "=", "rhs", ",", "ident", "=", "'r'", ",", ...
Disconnect all nodes :return:
[ "Disconnect", "all", "nodes" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/relationship_manager.py#L226-L235
train
206,785
neo4j-contrib/neomodel
neomodel/cardinality.py
ZeroOrOne.connect
def connect(self, node, properties=None): """ Connect to a node. :param node: :type: StructuredNode :param properties: relationship properties :type: dict :return: True / rel instance """ if len(self): raise AttemptedCardinalityViolation( "Node already has {0} can't connect more".format(self)) else: return super(ZeroOrOne, self).connect(node, properties)
python
def connect(self, node, properties=None): """ Connect to a node. :param node: :type: StructuredNode :param properties: relationship properties :type: dict :return: True / rel instance """ if len(self): raise AttemptedCardinalityViolation( "Node already has {0} can't connect more".format(self)) else: return super(ZeroOrOne, self).connect(node, properties)
[ "def", "connect", "(", "self", ",", "node", ",", "properties", "=", "None", ")", ":", "if", "len", "(", "self", ")", ":", "raise", "AttemptedCardinalityViolation", "(", "\"Node already has {0} can't connect more\"", ".", "format", "(", "self", ")", ")", "else"...
Connect to a node. :param node: :type: StructuredNode :param properties: relationship properties :type: dict :return: True / rel instance
[ "Connect", "to", "a", "node", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/cardinality.py#L29-L43
train
206,786
neo4j-contrib/neomodel
neomodel/cardinality.py
OneOrMore.single
def single(self): """ Fetch one of the related nodes :return: Node """ nodes = super(OneOrMore, self).all() if nodes: return nodes[0] raise CardinalityViolation(self, 'none')
python
def single(self): """ Fetch one of the related nodes :return: Node """ nodes = super(OneOrMore, self).all() if nodes: return nodes[0] raise CardinalityViolation(self, 'none')
[ "def", "single", "(", "self", ")", ":", "nodes", "=", "super", "(", "OneOrMore", ",", "self", ")", ".", "all", "(", ")", "if", "nodes", ":", "return", "nodes", "[", "0", "]", "raise", "CardinalityViolation", "(", "self", ",", "'none'", ")" ]
Fetch one of the related nodes :return: Node
[ "Fetch", "one", "of", "the", "related", "nodes" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/cardinality.py#L50-L59
train
206,787
neo4j-contrib/neomodel
neomodel/core.py
drop_indexes
def drop_indexes(quiet=True, stdout=None): """ Discover and drop all indexes. :type: bool :return: None """ results, meta = db.cypher_query("CALL db.indexes()") pattern = re.compile(':(.*)\((.*)\)') for index in results: db.cypher_query('DROP ' + index[0]) match = pattern.search(index[0]) stdout.write(' - Dropping index on label {0} with property {1}.\n'.format( match.group(1), match.group(2))) stdout.write("\n")
python
def drop_indexes(quiet=True, stdout=None): """ Discover and drop all indexes. :type: bool :return: None """ results, meta = db.cypher_query("CALL db.indexes()") pattern = re.compile(':(.*)\((.*)\)') for index in results: db.cypher_query('DROP ' + index[0]) match = pattern.search(index[0]) stdout.write(' - Dropping index on label {0} with property {1}.\n'.format( match.group(1), match.group(2))) stdout.write("\n")
[ "def", "drop_indexes", "(", "quiet", "=", "True", ",", "stdout", "=", "None", ")", ":", "results", ",", "meta", "=", "db", ".", "cypher_query", "(", "\"CALL db.indexes()\"", ")", "pattern", "=", "re", ".", "compile", "(", "':(.*)\\((.*)\\)'", ")", "for", ...
Discover and drop all indexes. :type: bool :return: None
[ "Discover", "and", "drop", "all", "indexes", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L32-L47
train
206,788
neo4j-contrib/neomodel
neomodel/core.py
remove_all_labels
def remove_all_labels(stdout=None): """ Calls functions for dropping constraints and indexes. :param stdout: output stream :return: None """ if not stdout: stdout = sys.stdout stdout.write("Droping constraints...\n") drop_constraints(quiet=False, stdout=stdout) stdout.write('Droping indexes...\n') drop_indexes(quiet=False, stdout=stdout)
python
def remove_all_labels(stdout=None): """ Calls functions for dropping constraints and indexes. :param stdout: output stream :return: None """ if not stdout: stdout = sys.stdout stdout.write("Droping constraints...\n") drop_constraints(quiet=False, stdout=stdout) stdout.write('Droping indexes...\n') drop_indexes(quiet=False, stdout=stdout)
[ "def", "remove_all_labels", "(", "stdout", "=", "None", ")", ":", "if", "not", "stdout", ":", "stdout", "=", "sys", ".", "stdout", "stdout", ".", "write", "(", "\"Droping constraints...\\n\"", ")", "drop_constraints", "(", "quiet", "=", "False", ",", "stdout...
Calls functions for dropping constraints and indexes. :param stdout: output stream :return: None
[ "Calls", "functions", "for", "dropping", "constraints", "and", "indexes", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L50-L65
train
206,789
neo4j-contrib/neomodel
neomodel/core.py
install_labels
def install_labels(cls, quiet=True, stdout=None): """ Setup labels with indexes and constraints for a given class :param cls: StructuredNode class :type: class :param quiet: (default true) enable standard output :param stdout: stdout stream :type: bool :return: None """ if not hasattr(cls, '__label__'): if not quiet: stdout.write(' ! Skipping class {0}.{1} is abstract\n'.format(cls.__module__, cls.__name__)) return for name, property in cls.defined_properties(aliases=False, rels=False).items(): db_property = property.db_property or name if property.index: if not quiet: stdout.write(' + Creating index {0} on label {1} for class {2}.{3}\n'.format( name, cls.__label__, cls.__module__, cls.__name__)) db.cypher_query("CREATE INDEX on :{0}({1}); ".format( cls.__label__, db_property)) elif property.unique_index: if not quiet: stdout.write(' + Creating unique constraint for {0} on label {1} for class {2}.{3}\n'.format( name, cls.__label__, cls.__module__, cls.__name__)) db.cypher_query("CREATE CONSTRAINT " "on (n:{0}) ASSERT n.{1} IS UNIQUE; ".format( cls.__label__, db_property))
python
def install_labels(cls, quiet=True, stdout=None): """ Setup labels with indexes and constraints for a given class :param cls: StructuredNode class :type: class :param quiet: (default true) enable standard output :param stdout: stdout stream :type: bool :return: None """ if not hasattr(cls, '__label__'): if not quiet: stdout.write(' ! Skipping class {0}.{1} is abstract\n'.format(cls.__module__, cls.__name__)) return for name, property in cls.defined_properties(aliases=False, rels=False).items(): db_property = property.db_property or name if property.index: if not quiet: stdout.write(' + Creating index {0} on label {1} for class {2}.{3}\n'.format( name, cls.__label__, cls.__module__, cls.__name__)) db.cypher_query("CREATE INDEX on :{0}({1}); ".format( cls.__label__, db_property)) elif property.unique_index: if not quiet: stdout.write(' + Creating unique constraint for {0} on label {1} for class {2}.{3}\n'.format( name, cls.__label__, cls.__module__, cls.__name__)) db.cypher_query("CREATE CONSTRAINT " "on (n:{0}) ASSERT n.{1} IS UNIQUE; ".format( cls.__label__, db_property))
[ "def", "install_labels", "(", "cls", ",", "quiet", "=", "True", ",", "stdout", "=", "None", ")", ":", "if", "not", "hasattr", "(", "cls", ",", "'__label__'", ")", ":", "if", "not", "quiet", ":", "stdout", ".", "write", "(", "' ! Skipping class {0}.{1} is...
Setup labels with indexes and constraints for a given class :param cls: StructuredNode class :type: class :param quiet: (default true) enable standard output :param stdout: stdout stream :type: bool :return: None
[ "Setup", "labels", "with", "indexes", "and", "constraints", "for", "a", "given", "class" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L68-L102
train
206,790
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode._build_merge_query
def _build_merge_query(cls, merge_params, update_existing=False, lazy=False, relationship=None): """ Get a tuple of a CYPHER query and a params dict for the specified MERGE query. :param merge_params: The target node match parameters, each node must have a "create" key and optional "update". :type merge_params: list of dict :param update_existing: True to update properties of existing nodes, default False to keep existing values. :type update_existing: bool :rtype: tuple """ query_params = dict(merge_params=merge_params) n_merge = "n:{0} {{{1}}}".format( ":".join(cls.inherited_labels()), ", ".join("{0}: params.create.{0}".format(getattr(cls, p).db_property or p) for p in cls.__required_properties__)) if relationship is None: # create "simple" unwind query query = "UNWIND {{merge_params}} as params\n MERGE ({0})\n ".format(n_merge) else: # validate relationship if not isinstance(relationship.source, StructuredNode): raise ValueError("relationship source [{0}] is not a StructuredNode".format(repr(relationship.source))) relation_type = relationship.definition.get('relation_type') if not relation_type: raise ValueError('No relation_type is specified on provided relationship') from .match import _rel_helper query_params["source_id"] = relationship.source.id query = "MATCH (source:{0}) WHERE ID(source) = {{source_id}}\n ".format(relationship.source.__label__) query += "WITH source\n UNWIND {merge_params} as params \n " query += "MERGE " query += _rel_helper(lhs='source', rhs=n_merge, ident=None, relation_type=relation_type, direction=relationship.definition['direction']) query += "ON CREATE SET n = params.create\n " # if update_existing, write properties on match as well if update_existing is True: query += "ON MATCH SET n += params.update\n" # close query if lazy: query += "RETURN id(n)" else: query += "RETURN n" return query, query_params
python
def _build_merge_query(cls, merge_params, update_existing=False, lazy=False, relationship=None): """ Get a tuple of a CYPHER query and a params dict for the specified MERGE query. :param merge_params: The target node match parameters, each node must have a "create" key and optional "update". :type merge_params: list of dict :param update_existing: True to update properties of existing nodes, default False to keep existing values. :type update_existing: bool :rtype: tuple """ query_params = dict(merge_params=merge_params) n_merge = "n:{0} {{{1}}}".format( ":".join(cls.inherited_labels()), ", ".join("{0}: params.create.{0}".format(getattr(cls, p).db_property or p) for p in cls.__required_properties__)) if relationship is None: # create "simple" unwind query query = "UNWIND {{merge_params}} as params\n MERGE ({0})\n ".format(n_merge) else: # validate relationship if not isinstance(relationship.source, StructuredNode): raise ValueError("relationship source [{0}] is not a StructuredNode".format(repr(relationship.source))) relation_type = relationship.definition.get('relation_type') if not relation_type: raise ValueError('No relation_type is specified on provided relationship') from .match import _rel_helper query_params["source_id"] = relationship.source.id query = "MATCH (source:{0}) WHERE ID(source) = {{source_id}}\n ".format(relationship.source.__label__) query += "WITH source\n UNWIND {merge_params} as params \n " query += "MERGE " query += _rel_helper(lhs='source', rhs=n_merge, ident=None, relation_type=relation_type, direction=relationship.definition['direction']) query += "ON CREATE SET n = params.create\n " # if update_existing, write properties on match as well if update_existing is True: query += "ON MATCH SET n += params.update\n" # close query if lazy: query += "RETURN id(n)" else: query += "RETURN n" return query, query_params
[ "def", "_build_merge_query", "(", "cls", ",", "merge_params", ",", "update_existing", "=", "False", ",", "lazy", "=", "False", ",", "relationship", "=", "None", ")", ":", "query_params", "=", "dict", "(", "merge_params", "=", "merge_params", ")", "n_merge", ...
Get a tuple of a CYPHER query and a params dict for the specified MERGE query. :param merge_params: The target node match parameters, each node must have a "create" key and optional "update". :type merge_params: list of dict :param update_existing: True to update properties of existing nodes, default False to keep existing values. :type update_existing: bool :rtype: tuple
[ "Get", "a", "tuple", "of", "a", "CYPHER", "query", "and", "a", "params", "dict", "for", "the", "specified", "MERGE", "query", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L250-L295
train
206,791
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.create
def create(cls, *props, **kwargs): """ Call to CREATE with parameters map. A new instance will be created and saved. :param props: dict of properties to create the nodes. :type props: tuple :param lazy: False by default, specify True to get nodes with id only without the parameters. :type: bool :rtype: list """ if 'streaming' in kwargs: warnings.warn('streaming is not supported by bolt, please remove the kwarg', category=DeprecationWarning, stacklevel=1) lazy = kwargs.get('lazy', False) # create mapped query query = "CREATE (n:{0} {{create_params}})".format(':'.join(cls.inherited_labels())) # close query if lazy: query += " RETURN id(n)" else: query += " RETURN n" results = [] for item in [cls.deflate(p, obj=_UnsavedNode(), skip_empty=True) for p in props]: node, _ = db.cypher_query(query, {'create_params': item}) results.extend(node[0]) nodes = [cls.inflate(node) for node in results] if not lazy and hasattr(cls, 'post_create'): for node in nodes: node.post_create() return nodes
python
def create(cls, *props, **kwargs): """ Call to CREATE with parameters map. A new instance will be created and saved. :param props: dict of properties to create the nodes. :type props: tuple :param lazy: False by default, specify True to get nodes with id only without the parameters. :type: bool :rtype: list """ if 'streaming' in kwargs: warnings.warn('streaming is not supported by bolt, please remove the kwarg', category=DeprecationWarning, stacklevel=1) lazy = kwargs.get('lazy', False) # create mapped query query = "CREATE (n:{0} {{create_params}})".format(':'.join(cls.inherited_labels())) # close query if lazy: query += " RETURN id(n)" else: query += " RETURN n" results = [] for item in [cls.deflate(p, obj=_UnsavedNode(), skip_empty=True) for p in props]: node, _ = db.cypher_query(query, {'create_params': item}) results.extend(node[0]) nodes = [cls.inflate(node) for node in results] if not lazy and hasattr(cls, 'post_create'): for node in nodes: node.post_create() return nodes
[ "def", "create", "(", "cls", ",", "*", "props", ",", "*", "*", "kwargs", ")", ":", "if", "'streaming'", "in", "kwargs", ":", "warnings", ".", "warn", "(", "'streaming is not supported by bolt, please remove the kwarg'", ",", "category", "=", "DeprecationWarning", ...
Call to CREATE with parameters map. A new instance will be created and saved. :param props: dict of properties to create the nodes. :type props: tuple :param lazy: False by default, specify True to get nodes with id only without the parameters. :type: bool :rtype: list
[ "Call", "to", "CREATE", "with", "parameters", "map", ".", "A", "new", "instance", "will", "be", "created", "and", "saved", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L303-L339
train
206,792
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.create_or_update
def create_or_update(cls, *props, **kwargs): """ Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. If an instance already exists all optional properties specified will be updated. Note that the post_create hook isn't called after create_or_update :param props: List of dict arguments to get or create the entities with. :type props: tuple :param relationship: Optional, relationship to get/create on when new entity is created. :param lazy: False by default, specify True to get nodes with id only without the parameters. :rtype: list """ lazy = kwargs.get('lazy', False) relationship = kwargs.get('relationship') # build merge query, make sure to update only explicitly specified properties create_or_update_params = [] for specified, deflated in [(p, cls.deflate(p, skip_empty=True)) for p in props]: create_or_update_params.append({"create": deflated, "update": dict((k, v) for k, v in deflated.items() if k in specified)}) query, params = cls._build_merge_query(create_or_update_params, update_existing=True, relationship=relationship, lazy=lazy) if 'streaming' in kwargs: warnings.warn('streaming is not supported by bolt, please remove the kwarg', category=DeprecationWarning, stacklevel=1) # fetch and build instance for each result results = db.cypher_query(query, params) return [cls.inflate(r[0]) for r in results[0]]
python
def create_or_update(cls, *props, **kwargs): """ Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. If an instance already exists all optional properties specified will be updated. Note that the post_create hook isn't called after create_or_update :param props: List of dict arguments to get or create the entities with. :type props: tuple :param relationship: Optional, relationship to get/create on when new entity is created. :param lazy: False by default, specify True to get nodes with id only without the parameters. :rtype: list """ lazy = kwargs.get('lazy', False) relationship = kwargs.get('relationship') # build merge query, make sure to update only explicitly specified properties create_or_update_params = [] for specified, deflated in [(p, cls.deflate(p, skip_empty=True)) for p in props]: create_or_update_params.append({"create": deflated, "update": dict((k, v) for k, v in deflated.items() if k in specified)}) query, params = cls._build_merge_query(create_or_update_params, update_existing=True, relationship=relationship, lazy=lazy) if 'streaming' in kwargs: warnings.warn('streaming is not supported by bolt, please remove the kwarg', category=DeprecationWarning, stacklevel=1) # fetch and build instance for each result results = db.cypher_query(query, params) return [cls.inflate(r[0]) for r in results[0]]
[ "def", "create_or_update", "(", "cls", ",", "*", "props", ",", "*", "*", "kwargs", ")", ":", "lazy", "=", "kwargs", ".", "get", "(", "'lazy'", ",", "False", ")", "relationship", "=", "kwargs", ".", "get", "(", "'relationship'", ")", "# build merge query,...
Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. If an instance already exists all optional properties specified will be updated. Note that the post_create hook isn't called after create_or_update :param props: List of dict arguments to get or create the entities with. :type props: tuple :param relationship: Optional, relationship to get/create on when new entity is created. :param lazy: False by default, specify True to get nodes with id only without the parameters. :rtype: list
[ "Call", "to", "MERGE", "with", "parameters", "map", ".", "A", "new", "instance", "will", "be", "created", "and", "saved", "if", "does", "not", "already", "exists", "this", "is", "an", "atomic", "operation", ".", "If", "an", "instance", "already", "exists",...
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L342-L372
train
206,793
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.cypher
def cypher(self, query, params=None): """ Execute a cypher query with the param 'self' pre-populated with the nodes neo4j id. :param query: cypher query string :type: string :param params: query parameters :type: dict :return: list containing query results :rtype: list """ self._pre_action_check('cypher') params = params or {} params.update({'self': self.id}) return db.cypher_query(query, params)
python
def cypher(self, query, params=None): """ Execute a cypher query with the param 'self' pre-populated with the nodes neo4j id. :param query: cypher query string :type: string :param params: query parameters :type: dict :return: list containing query results :rtype: list """ self._pre_action_check('cypher') params = params or {} params.update({'self': self.id}) return db.cypher_query(query, params)
[ "def", "cypher", "(", "self", ",", "query", ",", "params", "=", "None", ")", ":", "self", ".", "_pre_action_check", "(", "'cypher'", ")", "params", "=", "params", "or", "{", "}", "params", ".", "update", "(", "{", "'self'", ":", "self", ".", "id", ...
Execute a cypher query with the param 'self' pre-populated with the nodes neo4j id. :param query: cypher query string :type: string :param params: query parameters :type: dict :return: list containing query results :rtype: list
[ "Execute", "a", "cypher", "query", "with", "the", "param", "self", "pre", "-", "populated", "with", "the", "nodes", "neo4j", "id", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L374-L388
train
206,794
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.delete
def delete(self): """ Delete a node and it's relationships :return: True """ self._pre_action_check('delete') self.cypher("MATCH (self) WHERE id(self)={self} " "OPTIONAL MATCH (self)-[r]-()" " DELETE r, self") delattr(self, 'id') self.deleted = True return True
python
def delete(self): """ Delete a node and it's relationships :return: True """ self._pre_action_check('delete') self.cypher("MATCH (self) WHERE id(self)={self} " "OPTIONAL MATCH (self)-[r]-()" " DELETE r, self") delattr(self, 'id') self.deleted = True return True
[ "def", "delete", "(", "self", ")", ":", "self", ".", "_pre_action_check", "(", "'delete'", ")", "self", ".", "cypher", "(", "\"MATCH (self) WHERE id(self)={self} \"", "\"OPTIONAL MATCH (self)-[r]-()\"", "\" DELETE r, self\"", ")", "delattr", "(", "self", ",", "'id'", ...
Delete a node and it's relationships :return: True
[ "Delete", "a", "node", "and", "it", "s", "relationships" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L391-L403
train
206,795
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.get_or_create
def get_or_create(cls, *props, **kwargs): """ Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. Parameters must contain all required properties, any non required properties with defaults will be generated. Note that the post_create hook isn't called after get_or_create :param props: dict of properties to get or create the entities with. :type props: tuple :param relationship: Optional, relationship to get/create on when new entity is created. :param lazy: False by default, specify True to get nodes with id only without the parameters. :rtype: list """ lazy = kwargs.get('lazy', False) relationship = kwargs.get('relationship') # build merge query get_or_create_params = [{"create": cls.deflate(p, skip_empty=True)} for p in props] query, params = cls._build_merge_query(get_or_create_params, relationship=relationship, lazy=lazy) if 'streaming' in kwargs: warnings.warn('streaming is not supported by bolt, please remove the kwarg', category=DeprecationWarning, stacklevel=1) # fetch and build instance for each result results = db.cypher_query(query, params) return [cls.inflate(r[0]) for r in results[0]]
python
def get_or_create(cls, *props, **kwargs): """ Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. Parameters must contain all required properties, any non required properties with defaults will be generated. Note that the post_create hook isn't called after get_or_create :param props: dict of properties to get or create the entities with. :type props: tuple :param relationship: Optional, relationship to get/create on when new entity is created. :param lazy: False by default, specify True to get nodes with id only without the parameters. :rtype: list """ lazy = kwargs.get('lazy', False) relationship = kwargs.get('relationship') # build merge query get_or_create_params = [{"create": cls.deflate(p, skip_empty=True)} for p in props] query, params = cls._build_merge_query(get_or_create_params, relationship=relationship, lazy=lazy) if 'streaming' in kwargs: warnings.warn('streaming is not supported by bolt, please remove the kwarg', category=DeprecationWarning, stacklevel=1) # fetch and build instance for each result results = db.cypher_query(query, params) return [cls.inflate(r[0]) for r in results[0]]
[ "def", "get_or_create", "(", "cls", ",", "*", "props", ",", "*", "*", "kwargs", ")", ":", "lazy", "=", "kwargs", ".", "get", "(", "'lazy'", ",", "False", ")", "relationship", "=", "kwargs", ".", "get", "(", "'relationship'", ")", "# build merge query", ...
Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. Parameters must contain all required properties, any non required properties with defaults will be generated. Note that the post_create hook isn't called after get_or_create :param props: dict of properties to get or create the entities with. :type props: tuple :param relationship: Optional, relationship to get/create on when new entity is created. :param lazy: False by default, specify True to get nodes with id only without the parameters. :rtype: list
[ "Call", "to", "MERGE", "with", "parameters", "map", ".", "A", "new", "instance", "will", "be", "created", "and", "saved", "if", "does", "not", "already", "exists", "this", "is", "an", "atomic", "operation", ".", "Parameters", "must", "contain", "all", "req...
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L406-L433
train
206,796
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.inherited_labels
def inherited_labels(cls): """ Return list of labels from nodes class hierarchy. :return: list """ return [scls.__label__ for scls in cls.mro() if hasattr(scls, '__label__') and not hasattr( scls, '__abstract_node__')]
python
def inherited_labels(cls): """ Return list of labels from nodes class hierarchy. :return: list """ return [scls.__label__ for scls in cls.mro() if hasattr(scls, '__label__') and not hasattr( scls, '__abstract_node__')]
[ "def", "inherited_labels", "(", "cls", ")", ":", "return", "[", "scls", ".", "__label__", "for", "scls", "in", "cls", ".", "mro", "(", ")", "if", "hasattr", "(", "scls", ",", "'__label__'", ")", "and", "not", "hasattr", "(", "scls", ",", "'__abstract_n...
Return list of labels from nodes class hierarchy. :return: list
[ "Return", "list", "of", "labels", "from", "nodes", "class", "hierarchy", "." ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L466-L474
train
206,797
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.refresh
def refresh(self): """ Reload the node from neo4j """ self._pre_action_check('refresh') if hasattr(self, 'id'): request = self.cypher("MATCH (n) WHERE id(n)={self}" " RETURN n")[0] if not request or not request[0]: raise self.__class__.DoesNotExist("Can't refresh non existent node") node = self.inflate(request[0][0]) for key, val in node.__properties__.items(): setattr(self, key, val) else: raise ValueError("Can't refresh unsaved node")
python
def refresh(self): """ Reload the node from neo4j """ self._pre_action_check('refresh') if hasattr(self, 'id'): request = self.cypher("MATCH (n) WHERE id(n)={self}" " RETURN n")[0] if not request or not request[0]: raise self.__class__.DoesNotExist("Can't refresh non existent node") node = self.inflate(request[0][0]) for key, val in node.__properties__.items(): setattr(self, key, val) else: raise ValueError("Can't refresh unsaved node")
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "_pre_action_check", "(", "'refresh'", ")", "if", "hasattr", "(", "self", ",", "'id'", ")", ":", "request", "=", "self", ".", "cypher", "(", "\"MATCH (n) WHERE id(n)={self}\"", "\" RETURN n\"", ")", "[", ...
Reload the node from neo4j
[ "Reload", "the", "node", "from", "neo4j" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L495-L509
train
206,798
neo4j-contrib/neomodel
neomodel/core.py
StructuredNode.save
def save(self): """ Save the node to neo4j or raise an exception :return: the node instance """ # create or update instance node if hasattr(self, 'id'): # update params = self.deflate(self.__properties__, self) query = "MATCH (n) WHERE id(n)={self} \n" query += "\n".join(["SET n.{0} = {{{1}}}".format(key, key) + "\n" for key in params.keys()]) for label in self.inherited_labels(): query += "SET n:`{0}`\n".format(label) self.cypher(query, params) elif hasattr(self, 'deleted') and self.deleted: raise ValueError("{0}.save() attempted on deleted node".format( self.__class__.__name__)) else: # create self.id = self.create(self.__properties__)[0].id return self
python
def save(self): """ Save the node to neo4j or raise an exception :return: the node instance """ # create or update instance node if hasattr(self, 'id'): # update params = self.deflate(self.__properties__, self) query = "MATCH (n) WHERE id(n)={self} \n" query += "\n".join(["SET n.{0} = {{{1}}}".format(key, key) + "\n" for key in params.keys()]) for label in self.inherited_labels(): query += "SET n:`{0}`\n".format(label) self.cypher(query, params) elif hasattr(self, 'deleted') and self.deleted: raise ValueError("{0}.save() attempted on deleted node".format( self.__class__.__name__)) else: # create self.id = self.create(self.__properties__)[0].id return self
[ "def", "save", "(", "self", ")", ":", "# create or update instance node", "if", "hasattr", "(", "self", ",", "'id'", ")", ":", "# update", "params", "=", "self", ".", "deflate", "(", "self", ".", "__properties__", ",", "self", ")", "query", "=", "\"MATCH (...
Save the node to neo4j or raise an exception :return: the node instance
[ "Save", "the", "node", "to", "neo4j", "or", "raise", "an", "exception" ]
cca5de4c4e90998293558b871b1b529095c91a38
https://github.com/neo4j-contrib/neomodel/blob/cca5de4c4e90998293558b871b1b529095c91a38/neomodel/core.py#L512-L534
train
206,799