prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: s <|fim_middle|> def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
elf.index = 0
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: r <|fim_middle|> self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
eturn
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": " <|fim_middle|> <|fim▁end|>
"" Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def <|fim_middle|>(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
post_config_hook
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _<|fim_middle|>self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
set_fortune(
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _<|fim_middle|>self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
set_motion(
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _<|fim_middle|>self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
set_wanda(
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def w<|fim_middle|>self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
anda_the_fish(
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def k<|fim_middle|>self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def on_click(self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
ill(
<|file_name|>wanda_the_fish.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display a fortune-telling, swimming fish. Wanda has no use what-so-ever. It only takes up disk space and compilation time, and if loaded, it also takes up precious bar space, memory, and cpu cycles. Anybody found using it should be promptly sent for a psychiatric evaluation. Configuration parameters: cache_timeout: refresh interval for this module (default 0) format: display format for this module (default '{nomotion}[{fortune} ]{wanda}{motion}') fortune_timeout: refresh interval for fortune (default 60) Format placeholders: {fortune} one of many aphorisms or vague prophecies {wanda} name of one of the most commonly kept freshwater aquarium fish {motion} biologically propelled motion through a liquid medium {nomotion} opposite behavior of motion to prevent modules from shifting Optional: fortune-mod: the fortune cookie program from bsd games Examples: ``` # disable motions when not in use wanda_the_fish { format = '[\?if=fortune {nomotion}][{fortune} ]' format += '{wanda}[\?if=fortune {motion}]' } # no updates, no motions, yes fortunes, you click wanda_the_fish { format = '[{fortune} ]{wanda}' cache_timeout = -1 } # wanda moves, fortunes stays wanda_the_fish { format = '[{fortune} ]{nomotion}{wanda}{motion}' } # wanda is swimming too fast, slow down wanda wanda_the_fish { cache_timeout = 2 } ``` @author lasers SAMPLE OUTPUT [ {'full_text': 'innovate, v.: To annoy people.'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] idle [ {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>3', 'color': '#ff8c00'}, ] py3status [ {'full_text': 'py3status is so cool!'}, {'full_text': ' <', 'color': '#ffa500'}, {'full_text': '\xba', 'color': '#add8e6'}, {'full_text': ',', 'color': '#ff8c00'}, {'full_text': '))', 'color': '#ffa500'}, {'full_text': '))>< ', 'color': '#ff8c00'}, ] """ from time import time class Py3status: """ """ # available configuration parameters cache_timeout = 0 format = "{nomotion}[{fortune} ]{wanda}{motion}" fortune_timeout = 60 def post_config_hook(self): body = ( "[\?color=orange&show <" "[\?color=lightblue&show º]" "[\?color=darkorange&show ,]))" "[\?color=darkorange&show ))>%s]]" ) wanda = [body % fin for fin in ("<", ">", "<", "3")] self.wanda = [self.py3.safe_format(x) for x in wanda] self.wanda_length = len(self.wanda) self.index = 0 self.fortune_command = ["fortune", "-as"] self.fortune = self.py3.storage_get("fortune") or None self.toggled = self.py3.storage_get("toggled") or False self.motions = {"motion": " ", "nomotion": ""} # deal with {new,old} timeout between storage fortune_timeout = self.py3.storage_get("fortune_timeout") timeout = None if self.fortune_timeout != fortune_timeout: timeout = time() + self.fortune_timeout self.time = ( timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout) ) def _set_fortune(self, state=None, new=False): if not self.fortune_command: return if new: try: fortune_data = self.py3.command_output(self.fortune_command) except self.py3.CommandError: self.fortune = "" self.fortune_command = None else: self.fortune = " ".join(fortune_data.split()) self.time = time() + self.fortune_timeout elif state is None: if self.toggled and time() >= self.time: self._set_fortune(new=True) else: self.toggled = state if state: self._set_fortune(new=True) else: self.fortune = None def _set_motion(self): for k in self.motions: self.motions[k] = "" if self.motions[k] else " " def _set_wanda(self): self.index += 1 if self.index >= self.wanda_length: self.index = 0 def wanda_the_fish(self): self._set_fortune() self._set_motion() self._set_wanda() return { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": self.py3.safe_format( self.format, { "fortune": self.fortune, "motion": self.motions["motion"], "nomotion": self.motions["nomotion"], "wanda": self.wanda[self.index], }, ), } def kill(self): self.py3.storage_set("toggled", self.toggled) self.py3.storage_set("fortune", self.fortune) self.py3.storage_set("fortune_timeout", self.fortune_timeout) self.py3.storage_set("time", self.time) def o<|fim_middle|>self, event): if not self.fortune_command: return self._set_fortune(not self.toggled) if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
n_click(
<|file_name|>test-xy.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import pygtk pygtk.require('2.0') import pynotify<|fim▁hole|> if not pynotify.init("XY"): sys.exit(1) n = pynotify.Notification("X, Y Test", "This notification should point to 150, 10") n.set_hint("x", 150) n.set_hint("y", 10) if not n.show(): print "Failed to send notification" sys.exit(1)<|fim▁end|>
import sys if __name__ == '__main__':
<|file_name|>test-xy.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import pygtk pygtk.require('2.0') import pynotify import sys if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
if not pynotify.init("XY"): sys.exit(1) n = pynotify.Notification("X, Y Test", "This notification should point to 150, 10") n.set_hint("x", 150) n.set_hint("y", 10) if not n.show(): print "Failed to send notification" sys.exit(1)
<|file_name|>test-xy.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import pygtk pygtk.require('2.0') import pynotify import sys if __name__ == '__main__': if not pynotify.init("XY"): <|fim_middle|> n = pynotify.Notification("X, Y Test", "This notification should point to 150, 10") n.set_hint("x", 150) n.set_hint("y", 10) if not n.show(): print "Failed to send notification" sys.exit(1) <|fim▁end|>
sys.exit(1)
<|file_name|>test-xy.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import pygtk pygtk.require('2.0') import pynotify import sys if __name__ == '__main__': if not pynotify.init("XY"): sys.exit(1) n = pynotify.Notification("X, Y Test", "This notification should point to 150, 10") n.set_hint("x", 150) n.set_hint("y", 10) if not n.show(): <|fim_middle|> <|fim▁end|>
print "Failed to send notification" sys.exit(1)
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages from codecs import open import os def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read()<|fim▁hole|> setup( name='transposer', version='0.0.3', description='Transposes columns and rows in delimited text files', long_description=(read('README.rst')), url='https://github.com/keithhamilton/transposer', author='Keith Hamilton', maintainer='Keith Hamilton', maintainer_email='[email protected]', license='BSD License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Office/Business' ], keywords='text, csv, tab-delimited, delimited, excel, sheet, spreadsheet', packages=find_packages(exclude=['contrib', 'docs', 'test*', 'bin', 'include', 'lib', '.idea']), install_requires=[], package_data={}, data_files=[], entry_points={ 'console_scripts': [ 'transposer=transposer.script.console_script:main' ] } )<|fim▁end|>
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages from codecs import open import os def read(*paths): <|fim_middle|> setup( name='transposer', version='0.0.3', description='Transposes columns and rows in delimited text files', long_description=(read('README.rst')), url='https://github.com/keithhamilton/transposer', author='Keith Hamilton', maintainer='Keith Hamilton', maintainer_email='[email protected]', license='BSD License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Office/Business' ], keywords='text, csv, tab-delimited, delimited, excel, sheet, spreadsheet', packages=find_packages(exclude=['contrib', 'docs', 'test*', 'bin', 'include', 'lib', '.idea']), install_requires=[], package_data={}, data_files=[], entry_points={ 'console_scripts': [ 'transposer=transposer.script.console_script:main' ] } ) <|fim▁end|>
"""Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read()
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages from codecs import open import os def <|fim_middle|>(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name='transposer', version='0.0.3', description='Transposes columns and rows in delimited text files', long_description=(read('README.rst')), url='https://github.com/keithhamilton/transposer', author='Keith Hamilton', maintainer='Keith Hamilton', maintainer_email='[email protected]', license='BSD License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Office/Business' ], keywords='text, csv, tab-delimited, delimited, excel, sheet, spreadsheet', packages=find_packages(exclude=['contrib', 'docs', 'test*', 'bin', 'include', 'lib', '.idea']), install_requires=[], package_data={}, data_files=[], entry_points={ 'console_scripts': [ 'transposer=transposer.script.console_script:main' ] } ) <|fim▁end|>
read
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>import os from setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-email-subscription', url='https://github.com/MagicSolutions/django-email-subscription', version='0.0.1', description='Django app for creating subcription accoutns.', long_description=README, install_requires=[ 'django-simple-captcha>=0.4.2', ], packages=find_packages(), package_data={'': ['LICENSE']}, include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers',<|fim▁hole|> 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', ], )<|fim▁end|>
<|file_name|>example_date_featurizer.py<|end_file_name|><|fim▁begin|>""" ================================================= Modeling quasi-seasonal trends with date features ================================================= Some trends are common enough to appear seasonal, yet sporadic enough that approaching them from a seasonal perspective may not be valid. An example of this is the `"end-of-the-month" effect <https://robjhyndman.com/hyndsight/monthly-seasonality/>`_. In this example, we'll explore how we can create meaningful features that express seasonal trends without needing to fit a seasonal model. .. raw:: html <br/> """ print(__doc__) # Author: Taylor Smith <[email protected]> import pmdarima as pm from pmdarima import arima from pmdarima import model_selection from pmdarima import pipeline from pmdarima import preprocessing from pmdarima.datasets._base import load_date_example import numpy as np from matplotlib import pyplot as plt print(f"pmdarima version: {pm.__version__}") # Load the data and split it into separate pieces y, X = load_date_example() y_train, y_test, X_train, X_test = \ model_selection.train_test_split(y, X, test_size=20) # We can examine traits about the time series: pm.tsdisplay(y_train, lag_max=10) # We can see the ACF increases and decreases rather rapidly, which means we may # need some differencing. There also does not appear to be an obvious seasonal # trend. n_diffs = arima.ndiffs(y_train, max_d=5) # Here's what the featurizer will create for us: date_feat = preprocessing.DateFeaturizer( column_name="date", # the name of the date feature in the X matrix with_day_of_week=True, with_day_of_month=True) _, X_train_feats = date_feat.fit_transform(y_train, X_train) print(f"Head of generated X features:\n{repr(X_train_feats.head())}") # We can plug this X featurizer into a pipeline: pipe = pipeline.Pipeline([ ('date', date_feat), ('arima', arima.AutoARIMA(d=n_diffs, trace=3, stepwise=True, suppress_warnings=True, seasonal=False)) ]) pipe.fit(y_train, X_train) # Plot our forecasts forecasts = pipe.predict(X=X_test) fig = plt.figure(figsize=(16, 8)) ax = fig.add_subplot(1, 1, 1) n_train = y_train.shape[0] x = np.arange(n_train + forecasts.shape[0]) ax.plot(x[:n_train], y_train, color='blue', label='Training Data') ax.plot(x[n_train:], forecasts, color='green', marker='o', label='Predicted') ax.plot(x[n_train:], y_test, color='red', label='Actual') ax.legend(loc='lower left', borderaxespad=0.5) ax.set_title('Predicted Foo') ax.set_ylabel('# Foo') plt.show() <|fim▁hole|># a model's predictive power.<|fim▁end|>
# What next? Try combining different featurizers in your pipeline to enhance
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) <|fim▁hole|> #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main()<|fim▁end|>
def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL':
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): <|fim_middle|> def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): <|fim_middle|> def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host)
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): <|fim_middle|> def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response)
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) <|fim_middle|> def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
print "STOP **************"
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): <|fim_middle|> def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze)
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): <|fim_middle|> def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze)
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): <|fim_middle|> def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() <|fim_middle|> def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName)
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): <|fim_middle|> if __name__ == '__main__': init() main() <|fim▁end|>
global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze <|fim_middle|> else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
self.register()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: <|fim_middle|> def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
response=raw_input("Enter your Senze:") self.sendDatagram(response)
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": <|fim_middle|> #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN <|fim_middle|> elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: <|fim_middle|> #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): <|fim_middle|> else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL'
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file <|fim_middle|> except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY'
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files <|fim_middle|> pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
cry.generateRSA(bits=1024)
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
init() main()
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def <|fim_middle|>(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
__init__
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def <|fim_middle|>(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
startProtocol
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def <|fim_middle|>(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
stopProtocol
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def <|fim_middle|>(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
register
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def <|fim_middle|>(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
sendDatagram
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def <|fim_middle|>(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
datagramReceived
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def <|fim_middle|>(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
init
<|file_name|>myDevice.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def <|fim_middle|>(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main() <|fim▁end|>
main
<|file_name|>analyzer.py<|end_file_name|><|fim▁begin|># Copyright (C) 2019 Fassio Blatter from stopeight import analyzer version=analyzer.version from stopeight.util.editor.data import ScribbleData def legal_segments(data):<|fim▁hole|>legal_segments.__annotations__ = {'data':ScribbleData,'return':ScribbleData}<|fim▁end|>
from stopeight.matrix import Vectors from stopeight.analyzer import legal_segments return legal_segments(Vectors(data)).__array__().view(ScribbleData)
<|file_name|>analyzer.py<|end_file_name|><|fim▁begin|># Copyright (C) 2019 Fassio Blatter from stopeight import analyzer version=analyzer.version from stopeight.util.editor.data import ScribbleData def legal_segments(data): <|fim_middle|> legal_segments.__annotations__ = {'data':ScribbleData,'return':ScribbleData} <|fim▁end|>
from stopeight.matrix import Vectors from stopeight.analyzer import legal_segments return legal_segments(Vectors(data)).__array__().view(ScribbleData)
<|file_name|>analyzer.py<|end_file_name|><|fim▁begin|># Copyright (C) 2019 Fassio Blatter from stopeight import analyzer version=analyzer.version from stopeight.util.editor.data import ScribbleData def <|fim_middle|>(data): from stopeight.matrix import Vectors from stopeight.analyzer import legal_segments return legal_segments(Vectors(data)).__array__().view(ScribbleData) legal_segments.__annotations__ = {'data':ScribbleData,'return':ScribbleData} <|fim▁end|>
legal_segments
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: <|fim▁hole|> @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved.<|fim▁end|>
class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: <|fim_middle|> # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): <|fim_middle|> @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
self._resistance = resistance self.voltage = voltage
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): <|fim_middle|> @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
return self._resistance
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): <|fim_middle|> @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
return self.voltage / self.resistance
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): <|fim_middle|> @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
self.voltage = self.resistance * value
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): <|fim_middle|> @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
return self.current * 1000
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): <|fim_middle|> # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
self.current = value / 1000
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': <|fim_middle|> # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!')
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: <|fim_middle|> # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!')
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def <|fim_middle|>(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
__init__
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def <|fim_middle|>(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
resistance
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def <|fim_middle|>(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
current
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def <|fim_middle|>(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
current
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def <|fim_middle|>(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
current_in_milliamps
<|file_name|>properties_extra.py<|end_file_name|><|fim▁begin|>''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def <|fim_middle|>(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved. <|fim▁end|>
current_in_milliamps
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """<|fim▁hole|> if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag<|fim▁end|>
require = cfg.get("require", require)
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): <|fim_middle|> class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
""" FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): <|fim_middle|> <|fim▁end|>
def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): <|fim_middle|> def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg)
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): <|fim_middle|> <|fim▁end|>
self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): <|fim_middle|> uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": <|fim_middle|> elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"]
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": <|fim_middle|> elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"]
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": <|fim_middle|> elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
self.features[v] = spike(self.data[self.varname])
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": <|fim_middle|> self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
self.features[v] = gradient(self.data[self.varname])
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def <|fim_middle|>(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
fuzzylogic
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def <|fim_middle|>(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def test(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
set_features
<|file_name|>fuzzylogic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Quality Control based on fuzzy logic. """ import logging import numpy as np from .core import QCCheckVar from .gradient import gradient from .spike import spike from .woa_normbias import woa_normbias from cotede.fuzzy import fuzzy_uncertainty module_logger = logging.getLogger(__name__) def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty class FuzzyLogic(QCCheckVar): def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg) def <|fim_middle|>(self): self.flags = {} cfg = self.cfg flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") uncertainty = self.features["fuzzylogic"] # FIXME: As it is now, it will have no zero flag value. Think about cases # where some values in a profile would not be estimated, hence flag=0 # I needed to use np.nonzeros because now uncertainty is a masked array, # to accept when a feature is masked. flag[np.nonzero(uncertainty <= 0.29)] = 1 flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2 flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3 flag[np.nonzero(uncertainty > 0.72)] = 4 self.flags["fuzzylogic"] = flag <|fim▁end|>
test
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def main(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results)<|fim▁hole|><|fim▁end|>
if __name__ == "__main__": main()
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): <|fim_middle|> def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def main(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results) if __name__ == "__main__": main() <|fim▁end|>
messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example <|fim_middle|> def main(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results) if __name__ == "__main__": main() <|fim▁end|>
messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def main(): <|fim_middle|> if __name__ == "__main__": main() <|fim▁end|>
fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results)
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def main(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results) if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
main()
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def <|fim_middle|>(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def main(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results) if __name__ == "__main__": main() <|fim▁end|>
first_message
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def <|fim_middle|>(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def main(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results) if __name__ == "__main__": main() <|fim▁end|>
generate_messages
<|file_name|>Write.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def <|fim_middle|>(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results) if __name__ == "__main__": main() <|fim▁end|>
main
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) )<|fim▁hole|> data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) ))<|fim▁end|>
def check_hosts(self, serializer):
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): <|fim_middle|> <|fim▁end|>
serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) ))
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): <|fim_middle|> def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
return CommandExecution.objects.filter( user_id=str(self.request.user.id) )
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): <|fim_middle|> def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg})
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): <|fim_middle|> def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request)
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): <|fim_middle|> <|fim▁end|>
self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) ))
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: <|fim_middle|> def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg})
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: <|fim_middle|> return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
return self.permission_denied(request, "Command execution disabled")
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def <|fim_middle|>(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
get_queryset
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def <|fim_middle|>(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
check_hosts
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def <|fim_middle|>(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
check_permissions
<|file_name|>command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def <|fim_middle|>(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) )) <|fim▁end|>
perform_create
<|file_name|>Gauss2.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Sep 21 16:29:34 2017 @author: ishort """ import math """ procedure to generate Gaussian of unit area when passed a FWHM""" #IDL: PRO GAUSS2,FWHM,LENGTH,NGAUS def gauss2(fwhm, length): #length=length*1l & FWHM=FWHM*1l #NGAUS=FLTARR(LENGTH) ngaus = [0.0 for i in range(length)] #This expression for CHAR comes from requiring f(x=0.5*FWHM)=0.5*f(x=0): #CHAR=-1d0*ALOG(0.5d0)/(0.5d0*0.5d0*FWHM*FWHM) char = -1.0 * math.log(0.5) / (0.5*0.5*fwhm*fwhm) <|fim▁hole|> #AMP=SQRT(CHAR/PI) amp = math.sqrt(char/math.pi) #FOR CNT=0l,(LENGTH-1) DO BEGIN # X=(CNT-LENGTH/2)*1.d0 # NGAUS(CNT)=AMP*EXP(-CHAR*X^2) #ENDFOR for cnt in range(length): x = 1.0 * (cnt - length/2) ngaus[cnt] = amp * math.exp(-1.0*char*x*x) return ngaus<|fim▁end|>
#This expression for AMP (amplitude) comes from requiring that the #area under the gaussian is unity:
<|file_name|>Gauss2.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Sep 21 16:29:34 2017 @author: ishort """ import math """ procedure to generate Gaussian of unit area when passed a FWHM""" #IDL: PRO GAUSS2,FWHM,LENGTH,NGAUS def gauss2(fwhm, length): #length=length*1l & FWHM=FWHM*1l #NGAUS=FLTARR(LENGTH) <|fim_middle|> <|fim▁end|>
ngaus = [0.0 for i in range(length)] #This expression for CHAR comes from requiring f(x=0.5*FWHM)=0.5*f(x=0): #CHAR=-1d0*ALOG(0.5d0)/(0.5d0*0.5d0*FWHM*FWHM) char = -1.0 * math.log(0.5) / (0.5*0.5*fwhm*fwhm) #This expression for AMP (amplitude) comes from requiring that the #area under the gaussian is unity: #AMP=SQRT(CHAR/PI) amp = math.sqrt(char/math.pi) #FOR CNT=0l,(LENGTH-1) DO BEGIN # X=(CNT-LENGTH/2)*1.d0 # NGAUS(CNT)=AMP*EXP(-CHAR*X^2) #ENDFOR for cnt in range(length): x = 1.0 * (cnt - length/2) ngaus[cnt] = amp * math.exp(-1.0*char*x*x) return ngaus