body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
e25ba4f6b2095c2f1ce12895b5e24a3e5a5fb72b44ada82be641e93e10127368
async def async_is_socket(self) -> bool: '\n Whether this path is a socket.\n ' try: stat = (await self.async_stat()) return S_ISSOCK(stat.st_mode) except OSError as e: if (not _ignore_error(e)): raise return False except ValueError: return False
Whether this path is a socket.
lazy/io/pathz_v2/base.py
async_is_socket
trisongz/lazycls
2
python
async def async_is_socket(self) -> bool: '\n \n ' try: stat = (await self.async_stat()) return S_ISSOCK(stat.st_mode) except OSError as e: if (not _ignore_error(e)): raise return False except ValueError: return False
async def async_is_socket(self) -> bool: '\n \n ' try: stat = (await self.async_stat()) return S_ISSOCK(stat.st_mode) except OSError as e: if (not _ignore_error(e)): raise return False except ValueError: return False<|docstring|>Whether this path is a socket.<|endoftext|>
21bc43f041b4235d4638bf90ac58ba84fcf06726ea0a9d9d86c9bd92322c1e83
def expanduser(self) -> PathzPath: ' Return a new path with expanded ~ and ~user constructs\n (as returned by os.path.expanduser)\n ' if ((not self._drv) and (not self._root) and self._parts and (self._parts[0][:1] == '~')): homedir = self._flavour.gethomedir(self._parts[0][1:]) return self._from_parts(([homedir] + self._parts[1:])) return self
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
lazy/io/pathz_v2/base.py
expanduser
trisongz/lazycls
2
python
def expanduser(self) -> PathzPath: ' Return a new path with expanded ~ and ~user constructs\n (as returned by os.path.expanduser)\n ' if ((not self._drv) and (not self._root) and self._parts and (self._parts[0][:1] == '~')): homedir = self._flavour.gethomedir(self._parts[0][1:]) return self._from_parts(([homedir] + self._parts[1:])) return self
def expanduser(self) -> PathzPath: ' Return a new path with expanded ~ and ~user constructs\n (as returned by os.path.expanduser)\n ' if ((not self._drv) and (not self._root) and self._parts and (self._parts[0][:1] == '~')): homedir = self._flavour.gethomedir(self._parts[0][1:]) return self._from_parts(([homedir] + self._parts[1:])) return self<|docstring|>Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)<|endoftext|>
bb4ebeac8a7d10b76f6685991d32d64ad317c792159a9b6d1359695acb0ac2ac
async def async_expanduser(self) -> PathzPath: ' Return a new path with expanded ~ and ~user constructs\n (as returned by os.path.expanduser)\n ' if ((not self._drv) and (not self._root) and self._parts and (self._parts[0][:1] == '~')): homedir = (await self._flavour.async_gethomedir(self._parts[0][1:])) return self._from_parts(([homedir] + self._parts[1:])) return self
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
lazy/io/pathz_v2/base.py
async_expanduser
trisongz/lazycls
2
python
async def async_expanduser(self) -> PathzPath: ' Return a new path with expanded ~ and ~user constructs\n (as returned by os.path.expanduser)\n ' if ((not self._drv) and (not self._root) and self._parts and (self._parts[0][:1] == '~')): homedir = (await self._flavour.async_gethomedir(self._parts[0][1:])) return self._from_parts(([homedir] + self._parts[1:])) return self
async def async_expanduser(self) -> PathzPath: ' Return a new path with expanded ~ and ~user constructs\n (as returned by os.path.expanduser)\n ' if ((not self._drv) and (not self._root) and self._parts and (self._parts[0][:1] == '~')): homedir = (await self._flavour.async_gethomedir(self._parts[0][1:])) return self._from_parts(([homedir] + self._parts[1:])) return self<|docstring|>Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)<|endoftext|>
5e3716c4aae893e3e1921c2a233480c3acb7a7695572141a7156832e0984edf1
def read_json(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n Reads JSON\n ' return Serialize.Json.loads(self.read_text(encoding=encoding), **kwargs)
Reads JSON
lazy/io/pathz_v2/base.py
read_json
trisongz/lazycls
2
python
def read_json(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return Serialize.Json.loads(self.read_text(encoding=encoding), **kwargs)
def read_json(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return Serialize.Json.loads(self.read_text(encoding=encoding), **kwargs)<|docstring|>Reads JSON<|endoftext|>
6d49f57ca3e7728c64957878a53ce44a864283910effe35134b4147695e66445
def read_jsonlines(self, mode: str='r', skip_errors: bool=True, as_iterable: bool=True, **kwargs) -> Iterator[T]: '\n Reads JSON Lines\n ' with self.open(mode=mode) as f: return Serialize.Json.readlines(f, as_iterable=as_iterable, skip_errors=skip_errors, **kwargs)
Reads JSON Lines
lazy/io/pathz_v2/base.py
read_jsonlines
trisongz/lazycls
2
python
def read_jsonlines(self, mode: str='r', skip_errors: bool=True, as_iterable: bool=True, **kwargs) -> Iterator[T]: '\n \n ' with self.open(mode=mode) as f: return Serialize.Json.readlines(f, as_iterable=as_iterable, skip_errors=skip_errors, **kwargs)
def read_jsonlines(self, mode: str='r', skip_errors: bool=True, as_iterable: bool=True, **kwargs) -> Iterator[T]: '\n \n ' with self.open(mode=mode) as f: return Serialize.Json.readlines(f, as_iterable=as_iterable, skip_errors=skip_errors, **kwargs)<|docstring|>Reads JSON Lines<|endoftext|>
94ca7f115b686654aeff177c101c9aef6a88f1008feb4a7ca4b22b71bb98eb43
def read_yaml(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n Reads YAML\n ' return Serialize.Yaml.loads(self.read_text(encoding=encoding), **kwargs)
Reads YAML
lazy/io/pathz_v2/base.py
read_yaml
trisongz/lazycls
2
python
def read_yaml(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return Serialize.Yaml.loads(self.read_text(encoding=encoding), **kwargs)
def read_yaml(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return Serialize.Yaml.loads(self.read_text(encoding=encoding), **kwargs)<|docstring|>Reads YAML<|endoftext|>
9f14f0b960a4135e7904f8e926cebb8cf837b5c806ba6cf159f3c0253afe2270
def read_pickle(self, mode: str='rb', **kwargs): '\n Reads Pickle File\n ' with self.open(mode=mode) as f: return Serialize.Pkl.loads(f.read(), **kwargs)
Reads Pickle File
lazy/io/pathz_v2/base.py
read_pickle
trisongz/lazycls
2
python
def read_pickle(self, mode: str='rb', **kwargs): '\n \n ' with self.open(mode=mode) as f: return Serialize.Pkl.loads(f.read(), **kwargs)
def read_pickle(self, mode: str='rb', **kwargs): '\n \n ' with self.open(mode=mode) as f: return Serialize.Pkl.loads(f.read(), **kwargs)<|docstring|>Reads Pickle File<|endoftext|>
9d3e1563dbb7e6176d3722a99fef36153b6c3165ab34aeafdd4d5ffc81988a65
def append_jsonlines(self, data: List[JsonType], encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n Appends JSON Lines to File\n ' if (ensure_file_exists and (not self.exists())): self.touch() with self.open(mode='a', encoding=encoding) as f: Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs)
Appends JSON Lines to File
lazy/io/pathz_v2/base.py
append_jsonlines
trisongz/lazycls
2
python
def append_jsonlines(self, data: List[JsonType], encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not self.exists())): self.touch() with self.open(mode='a', encoding=encoding) as f: Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs)
def append_jsonlines(self, data: List[JsonType], encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not self.exists())): self.touch() with self.open(mode='a', encoding=encoding) as f: Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs)<|docstring|>Appends JSON Lines to File<|endoftext|>
6f33e3571b5bf70aa0c12b76a59c4e1119df3734c13cf69a1d00deb1f52d6597
def write_json(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, ensure_ascii: bool=False, indent: int=2, **kwargs) -> None: '\n Writes JSON to File\n ' with self.open('w', encoding=encoding) as f: f.write(Serialize.SimdJson.dumps(data, ensure_ascii=ensure_ascii, indent=indent, **kwargs))
Writes JSON to File
lazy/io/pathz_v2/base.py
write_json
trisongz/lazycls
2
python
def write_json(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, ensure_ascii: bool=False, indent: int=2, **kwargs) -> None: '\n \n ' with self.open('w', encoding=encoding) as f: f.write(Serialize.SimdJson.dumps(data, ensure_ascii=ensure_ascii, indent=indent, **kwargs))
def write_json(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, ensure_ascii: bool=False, indent: int=2, **kwargs) -> None: '\n \n ' with self.open('w', encoding=encoding) as f: f.write(Serialize.SimdJson.dumps(data, ensure_ascii=ensure_ascii, indent=indent, **kwargs))<|docstring|>Writes JSON to File<|endoftext|>
d65fd53e045af30e41b602d8787ce7d269ef737651926f549c98bb10410788c6
def write_jsonlines(self, data: List[JsonType], append: bool=False, encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n Writes JSON Lines to File\n ' if (ensure_file_exists and (not self.exists())): self.touch() mode = ('a' if ((append and self.exists()) or ensure_file_exists) else 'w') with self.open(mode=mode, encoding=encoding) as f: Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs)
Writes JSON Lines to File
lazy/io/pathz_v2/base.py
write_jsonlines
trisongz/lazycls
2
python
def write_jsonlines(self, data: List[JsonType], append: bool=False, encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not self.exists())): self.touch() mode = ('a' if ((append and self.exists()) or ensure_file_exists) else 'w') with self.open(mode=mode, encoding=encoding) as f: Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs)
def write_jsonlines(self, data: List[JsonType], append: bool=False, encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not self.exists())): self.touch() mode = ('a' if ((append and self.exists()) or ensure_file_exists) else 'w') with self.open(mode=mode, encoding=encoding) as f: Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs)<|docstring|>Writes JSON Lines to File<|endoftext|>
eb88007fadef03ad871e71e8b258121cfd3b2999f2dfe211e22ee5d59fccea50
def write_yaml(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> None: '\n Writes YAML to File\n ' with self.open('w', encoding=encoding) as f: f.write(Serialize.Yaml.dumps(data, **kwargs))
Writes YAML to File
lazy/io/pathz_v2/base.py
write_yaml
trisongz/lazycls
2
python
def write_yaml(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> None: '\n \n ' with self.open('w', encoding=encoding) as f: f.write(Serialize.Yaml.dumps(data, **kwargs))
def write_yaml(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> None: '\n \n ' with self.open('w', encoding=encoding) as f: f.write(Serialize.Yaml.dumps(data, **kwargs))<|docstring|>Writes YAML to File<|endoftext|>
3dee812549f6d27d9605fc9122c369102264b4b8e99f9ab4cb3148b29970e4d2
def write_pickle(self, obj: Any, **kwargs) -> None: '\n Writes Pickle to File\n ' data = Serialize.Pkl.dumps(obj, **kwargs) return self.write_bytes(data)
Writes Pickle to File
lazy/io/pathz_v2/base.py
write_pickle
trisongz/lazycls
2
python
def write_pickle(self, obj: Any, **kwargs) -> None: '\n \n ' data = Serialize.Pkl.dumps(obj, **kwargs) return self.write_bytes(data)
def write_pickle(self, obj: Any, **kwargs) -> None: '\n \n ' data = Serialize.Pkl.dumps(obj, **kwargs) return self.write_bytes(data)<|docstring|>Writes Pickle to File<|endoftext|>
72c27eaa3fd87b1968a9746cbe0fcdaa722cd975c1382393e73b4c410e33a87c
async def async_read_json(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n Reads JSON Asyncronously\n ' return (await Serialize.Json.async_loads((await self.async_read_text(encoding=encoding)), **kwargs))
Reads JSON Asyncronously
lazy/io/pathz_v2/base.py
async_read_json
trisongz/lazycls
2
python
async def async_read_json(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return (await Serialize.Json.async_loads((await self.async_read_text(encoding=encoding)), **kwargs))
async def async_read_json(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return (await Serialize.Json.async_loads((await self.async_read_text(encoding=encoding)), **kwargs))<|docstring|>Reads JSON Asyncronously<|endoftext|>
63160c9445781a397d7385a2ee30ef0d048269c8e7954df48cba25615686326e
async def async_read_jsonlines(self, mode: str='r', skip_errors: bool=True, as_iterable: bool=True, **kwargs) -> Iterator[T]: '\n Reads JSON Lines Asyncronously\n ' async with self.async_open(mode=mode) as f: return (await Serialize.Json.async_readlines(f, as_iterable=as_iterable, skip_errors=skip_errors, **kwargs))
Reads JSON Lines Asyncronously
lazy/io/pathz_v2/base.py
async_read_jsonlines
trisongz/lazycls
2
python
async def async_read_jsonlines(self, mode: str='r', skip_errors: bool=True, as_iterable: bool=True, **kwargs) -> Iterator[T]: '\n \n ' async with self.async_open(mode=mode) as f: return (await Serialize.Json.async_readlines(f, as_iterable=as_iterable, skip_errors=skip_errors, **kwargs))
async def async_read_jsonlines(self, mode: str='r', skip_errors: bool=True, as_iterable: bool=True, **kwargs) -> Iterator[T]: '\n \n ' async with self.async_open(mode=mode) as f: return (await Serialize.Json.async_readlines(f, as_iterable=as_iterable, skip_errors=skip_errors, **kwargs))<|docstring|>Reads JSON Lines Asyncronously<|endoftext|>
31cd7afd0292273e35d27724b2cf886b04cc21832eddc6d5a6dd9fb893b59f3c
async def async_read_yaml(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n Reads YAML Asyncronously\n ' return (await Serialize.Yaml.async_loads((await self.async_read_text(encoding=encoding)), **kwargs))
Reads YAML Asyncronously
lazy/io/pathz_v2/base.py
async_read_yaml
trisongz/lazycls
2
python
async def async_read_yaml(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return (await Serialize.Yaml.async_loads((await self.async_read_text(encoding=encoding)), **kwargs))
async def async_read_yaml(self, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> JsonType: '\n \n ' return (await Serialize.Yaml.async_loads((await self.async_read_text(encoding=encoding)), **kwargs))<|docstring|>Reads YAML Asyncronously<|endoftext|>
d0336bc0c597e60674568d665e0c4ce634fcc85366222022d3a83e74950a9e92
async def async_read_pickle(self, mode: str='rb', **kwargs): '\n Reads Pickle File Asyncronously\n ' async with self.async_open(mode=mode) as f: return (await Serialize.Pkl.async_loads((await f.read()), **kwargs))
Reads Pickle File Asyncronously
lazy/io/pathz_v2/base.py
async_read_pickle
trisongz/lazycls
2
python
async def async_read_pickle(self, mode: str='rb', **kwargs): '\n \n ' async with self.async_open(mode=mode) as f: return (await Serialize.Pkl.async_loads((await f.read()), **kwargs))
async def async_read_pickle(self, mode: str='rb', **kwargs): '\n \n ' async with self.async_open(mode=mode) as f: return (await Serialize.Pkl.async_loads((await f.read()), **kwargs))<|docstring|>Reads Pickle File Asyncronously<|endoftext|>
26d6977a5c3c97d40d979128a01bcffac8fdec142a14d3b064a886635b82df21
async def async_append_jsonlines(self, data: List[JsonType], encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n Appends JSON Lines to File Asyncronously\n ' if (ensure_file_exists and (not (await self.async_exists_))): (await self.async_touch()) async with self.async_open(mode='a', encoding=encoding) as f: (await Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs))
Appends JSON Lines to File Asyncronously
lazy/io/pathz_v2/base.py
async_append_jsonlines
trisongz/lazycls
2
python
async def async_append_jsonlines(self, data: List[JsonType], encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not (await self.async_exists_))): (await self.async_touch()) async with self.async_open(mode='a', encoding=encoding) as f: (await Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs))
async def async_append_jsonlines(self, data: List[JsonType], encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not (await self.async_exists_))): (await self.async_touch()) async with self.async_open(mode='a', encoding=encoding) as f: (await Serialize.Json.write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs))<|docstring|>Appends JSON Lines to File Asyncronously<|endoftext|>
2fb404df23d4863101c279dcb6212659d289a5cb362b93e00b74c3849fc3dc9d
async def async_write_json(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, ensure_ascii: bool=False, indent: int=2, **kwargs) -> None: '\n Writes JSON to File Asyncronously\n ' async with self.async_open('w', encoding=encoding) as f: (await f.write((await Serialize.SimdJson.async_dumps(data, ensure_ascii=ensure_ascii, indent=indent, **kwargs))))
Writes JSON to File Asyncronously
lazy/io/pathz_v2/base.py
async_write_json
trisongz/lazycls
2
python
async def async_write_json(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, ensure_ascii: bool=False, indent: int=2, **kwargs) -> None: '\n \n ' async with self.async_open('w', encoding=encoding) as f: (await f.write((await Serialize.SimdJson.async_dumps(data, ensure_ascii=ensure_ascii, indent=indent, **kwargs))))
async def async_write_json(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, ensure_ascii: bool=False, indent: int=2, **kwargs) -> None: '\n \n ' async with self.async_open('w', encoding=encoding) as f: (await f.write((await Serialize.SimdJson.async_dumps(data, ensure_ascii=ensure_ascii, indent=indent, **kwargs))))<|docstring|>Writes JSON to File Asyncronously<|endoftext|>
01e3088b46baabf98e47a5bea864d36909a1c42e11504a4336dbd3aa6d590af2
async def async_write_jsonlines(self, data: List[JsonType], append: bool=False, encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n Writes JSON Lines to File Asyncronously\n ' if (ensure_file_exists and (not (await self.async_exists_))): (await self.async_touch()) mode = ('a' if ((append and (await self.async_exists_)) or ensure_file_exists) else 'w') async with self.async_open(mode=mode, encoding=encoding) as f: (await Serialize.Json.async_write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs))
Writes JSON Lines to File Asyncronously
lazy/io/pathz_v2/base.py
async_write_jsonlines
trisongz/lazycls
2
python
async def async_write_jsonlines(self, data: List[JsonType], append: bool=False, encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not (await self.async_exists_))): (await self.async_touch()) mode = ('a' if ((append and (await self.async_exists_)) or ensure_file_exists) else 'w') async with self.async_open(mode=mode, encoding=encoding) as f: (await Serialize.Json.async_write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs))
async def async_write_jsonlines(self, data: List[JsonType], append: bool=False, encoding: Optional[str]=DEFAULT_ENCODING, newline: str='\n', ignore_errors: bool=True, ensure_file_exists: bool=True, flush_every: int=0, log_errors: bool=False, **kwargs): '\n \n ' if (ensure_file_exists and (not (await self.async_exists_))): (await self.async_touch()) mode = ('a' if ((append and (await self.async_exists_)) or ensure_file_exists) else 'w') async with self.async_open(mode=mode, encoding=encoding) as f: (await Serialize.Json.async_write_jsonlines(f, data=data, newline=newline, ignore_errors=ignore_errors, flush_every=flush_every, log_errors=log_errors, **kwargs))<|docstring|>Writes JSON Lines to File Asyncronously<|endoftext|>
672e2f55057c281419df114de8ea8427eabc71f7e630eb03f04052f9d6e32a13
async def async_write_yaml(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> None: '\n Writes YAML to File Asyncronously\n ' async with self.async_open('w', encoding=encoding) as f: (await f.write((await Serialize.Yaml.async_dumps(data, **kwargs))))
Writes YAML to File Asyncronously
lazy/io/pathz_v2/base.py
async_write_yaml
trisongz/lazycls
2
python
async def async_write_yaml(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> None: '\n \n ' async with self.async_open('w', encoding=encoding) as f: (await f.write((await Serialize.Yaml.async_dumps(data, **kwargs))))
async def async_write_yaml(self, data: JsonType, encoding: Optional[str]=DEFAULT_ENCODING, **kwargs) -> None: '\n \n ' async with self.async_open('w', encoding=encoding) as f: (await f.write((await Serialize.Yaml.async_dumps(data, **kwargs))))<|docstring|>Writes YAML to File Asyncronously<|endoftext|>
c9f77de318edb517c204392a19a3ac570383084ac3f921a8845e3a2576b301cc
async def async_write_pickle(self, obj: Any, **kwargs) -> None: '\n Writes Pickle to File Asyncronously\n ' data = (await Serialize.Pkl.async_dumps(obj, **kwargs)) return (await self.async_write_bytes(data))
Writes Pickle to File Asyncronously
lazy/io/pathz_v2/base.py
async_write_pickle
trisongz/lazycls
2
python
async def async_write_pickle(self, obj: Any, **kwargs) -> None: '\n \n ' data = (await Serialize.Pkl.async_dumps(obj, **kwargs)) return (await self.async_write_bytes(data))
async def async_write_pickle(self, obj: Any, **kwargs) -> None: '\n \n ' data = (await Serialize.Pkl.async_dumps(obj, **kwargs)) return (await self.async_write_bytes(data))<|docstring|>Writes Pickle to File Asyncronously<|endoftext|>
457d69344c6ec2ff5c6cd6ee8cdff615f24cc5b8106e83b7cf421f9cca42a619
def __init__(self, tarball_name, package=None): '\n A (third-party downloadable) tarball\n\n Note that the tarball might also be a different kind of\n archive format that is supported, it does not necessarily have\n to be tar.\n\n INPUT:\n\n - ``tarball_name`` - string. The full filename (``foo-1.3.tar.bz2``)\n of a tarball on the Sage mirror network.\n ' self.__filename = tarball_name if (package is None): self.__package = None for pkg in Package.all(): if (pkg.tarball_filename == tarball_name): self.__package = pkg.tarball_package if (self.package is None): error = 'tarball {0} is not referenced by any Sage package'.format(tarball_name) log.error(error) raise ValueError(error) else: self.__package = package if (package.tarball_filename != tarball_name): error = 'tarball {0} is not referenced by the {1} package'.format(tarball_name, package.name) log.error(error) raise ValueError(error)
A (third-party downloadable) tarball Note that the tarball might also be a different kind of archive format that is supported, it does not necessarily have to be tar. INPUT: - ``tarball_name`` - string. The full filename (``foo-1.3.tar.bz2``) of a tarball on the Sage mirror network.
build/sage_bootstrap/tarball.py
__init__
velasjk3/SageMath
1,742
python
def __init__(self, tarball_name, package=None): '\n A (third-party downloadable) tarball\n\n Note that the tarball might also be a different kind of\n archive format that is supported, it does not necessarily have\n to be tar.\n\n INPUT:\n\n - ``tarball_name`` - string. The full filename (``foo-1.3.tar.bz2``)\n of a tarball on the Sage mirror network.\n ' self.__filename = tarball_name if (package is None): self.__package = None for pkg in Package.all(): if (pkg.tarball_filename == tarball_name): self.__package = pkg.tarball_package if (self.package is None): error = 'tarball {0} is not referenced by any Sage package'.format(tarball_name) log.error(error) raise ValueError(error) else: self.__package = package if (package.tarball_filename != tarball_name): error = 'tarball {0} is not referenced by the {1} package'.format(tarball_name, package.name) log.error(error) raise ValueError(error)
def __init__(self, tarball_name, package=None): '\n A (third-party downloadable) tarball\n\n Note that the tarball might also be a different kind of\n archive format that is supported, it does not necessarily have\n to be tar.\n\n INPUT:\n\n - ``tarball_name`` - string. The full filename (``foo-1.3.tar.bz2``)\n of a tarball on the Sage mirror network.\n ' self.__filename = tarball_name if (package is None): self.__package = None for pkg in Package.all(): if (pkg.tarball_filename == tarball_name): self.__package = pkg.tarball_package if (self.package is None): error = 'tarball {0} is not referenced by any Sage package'.format(tarball_name) log.error(error) raise ValueError(error) else: self.__package = package if (package.tarball_filename != tarball_name): error = 'tarball {0} is not referenced by the {1} package'.format(tarball_name, package.name) log.error(error) raise ValueError(error)<|docstring|>A (third-party downloadable) tarball Note that the tarball might also be a different kind of archive format that is supported, it does not necessarily have to be tar. INPUT: - ``tarball_name`` - string. The full filename (``foo-1.3.tar.bz2``) of a tarball on the Sage mirror network.<|endoftext|>
9c70adb382bb78ea5d3b0b6c4295765da6568d6b8b52cc45ad40f14b772f0c7e
@property def filename(self): '\n Return the tarball filename\n\n OUTPUT:\n\n String. The full filename (``foo-1.3.tar.bz2``) of the\n tarball.\n ' return self.__filename
Return the tarball filename OUTPUT: String. The full filename (``foo-1.3.tar.bz2``) of the tarball.
build/sage_bootstrap/tarball.py
filename
velasjk3/SageMath
1,742
python
@property def filename(self): '\n Return the tarball filename\n\n OUTPUT:\n\n String. The full filename (``foo-1.3.tar.bz2``) of the\n tarball.\n ' return self.__filename
@property def filename(self): '\n Return the tarball filename\n\n OUTPUT:\n\n String. The full filename (``foo-1.3.tar.bz2``) of the\n tarball.\n ' return self.__filename<|docstring|>Return the tarball filename OUTPUT: String. The full filename (``foo-1.3.tar.bz2``) of the tarball.<|endoftext|>
f70f63f337b7bd424e88b1f5cba3d76c9999a78161dd91e04f33cc5271b4628a
@property def package(self): '\n Return the package that the tarball belongs to\n\n OUTPUT:\n\n Instance of :class:`sage_bootstrap.package.Package`\n ' return self.__package
Return the package that the tarball belongs to OUTPUT: Instance of :class:`sage_bootstrap.package.Package`
build/sage_bootstrap/tarball.py
package
velasjk3/SageMath
1,742
python
@property def package(self): '\n Return the package that the tarball belongs to\n\n OUTPUT:\n\n Instance of :class:`sage_bootstrap.package.Package`\n ' return self.__package
@property def package(self): '\n Return the package that the tarball belongs to\n\n OUTPUT:\n\n Instance of :class:`sage_bootstrap.package.Package`\n ' return self.__package<|docstring|>Return the package that the tarball belongs to OUTPUT: Instance of :class:`sage_bootstrap.package.Package`<|endoftext|>
a6e20b9a128c1591fe05eea330f0bcb036f3ab8c8cb439de0096e6537e7b2359
@property def upstream_fqn(self): '\n The fully-qualified (including directory) file name in the upstream directory.\n ' return os.path.join(SAGE_DISTFILES, self.filename)
The fully-qualified (including directory) file name in the upstream directory.
build/sage_bootstrap/tarball.py
upstream_fqn
velasjk3/SageMath
1,742
python
@property def upstream_fqn(self): '\n \n ' return os.path.join(SAGE_DISTFILES, self.filename)
@property def upstream_fqn(self): '\n \n ' return os.path.join(SAGE_DISTFILES, self.filename)<|docstring|>The fully-qualified (including directory) file name in the upstream directory.<|endoftext|>
135430a9f966d816e98ea743b52075444cc3ebb10f8edc2572d418d93276c157
def checksum_verifies(self): '\n Test whether the checksum of the downloaded file is correct.\n ' sha1 = self._compute_sha1() return (sha1 == self.package.sha1)
Test whether the checksum of the downloaded file is correct.
build/sage_bootstrap/tarball.py
checksum_verifies
velasjk3/SageMath
1,742
python
def checksum_verifies(self): '\n \n ' sha1 = self._compute_sha1() return (sha1 == self.package.sha1)
def checksum_verifies(self): '\n \n ' sha1 = self._compute_sha1() return (sha1 == self.package.sha1)<|docstring|>Test whether the checksum of the downloaded file is correct.<|endoftext|>
7d951b20852015d0f7e0684c86a91692a5a7ad2902beaf1aa129ecded1825064
def download(self, allow_upstream=False): '\n Download the tarball to the upstream directory.\n\n If allow_upstream is False and the package cannot be found\n on the sage mirrors, fall back to downloading it from\n the upstream URL if the package has one.\n ' if (not self.filename): raise ValueError('non-normal package does define a tarball, so cannot download') destination = self.upstream_fqn if os.path.isfile(destination): if self.checksum_verifies(): log.info('Using cached file {destination}'.format(destination=destination)) return else: log.warning('Invalid checksum; ignoring cached file {destination}'.format(destination=destination)) successful_download = False log.info('Attempting to download package {0} from mirrors'.format(self.filename)) for mirror in MirrorList(): url = (mirror + '/'.join(['spkg', 'upstream', self.package.name, self.filename])) log.info(url) try: Download(url, destination).run() successful_download = True break except IOError: log.debug('File not on mirror') if (not successful_download): url = self.package.tarball_upstream_url if (allow_upstream and url): log.info('Attempting to download from {}'.format(url)) try: Download(url, destination).run() successful_download = True except IOError: raise FileNotMirroredError('tarball does not exist on mirror network and neither at the upstream URL') else: raise FileNotMirroredError('tarball does not exist on mirror network') if (not self.checksum_verifies()): raise ChecksumError('checksum does not match')
Download the tarball to the upstream directory. If allow_upstream is False and the package cannot be found on the sage mirrors, fall back to downloading it from the upstream URL if the package has one.
build/sage_bootstrap/tarball.py
download
velasjk3/SageMath
1,742
python
def download(self, allow_upstream=False): '\n Download the tarball to the upstream directory.\n\n If allow_upstream is False and the package cannot be found\n on the sage mirrors, fall back to downloading it from\n the upstream URL if the package has one.\n ' if (not self.filename): raise ValueError('non-normal package does define a tarball, so cannot download') destination = self.upstream_fqn if os.path.isfile(destination): if self.checksum_verifies(): log.info('Using cached file {destination}'.format(destination=destination)) return else: log.warning('Invalid checksum; ignoring cached file {destination}'.format(destination=destination)) successful_download = False log.info('Attempting to download package {0} from mirrors'.format(self.filename)) for mirror in MirrorList(): url = (mirror + '/'.join(['spkg', 'upstream', self.package.name, self.filename])) log.info(url) try: Download(url, destination).run() successful_download = True break except IOError: log.debug('File not on mirror') if (not successful_download): url = self.package.tarball_upstream_url if (allow_upstream and url): log.info('Attempting to download from {}'.format(url)) try: Download(url, destination).run() successful_download = True except IOError: raise FileNotMirroredError('tarball does not exist on mirror network and neither at the upstream URL') else: raise FileNotMirroredError('tarball does not exist on mirror network') if (not self.checksum_verifies()): raise ChecksumError('checksum does not match')
def download(self, allow_upstream=False): '\n Download the tarball to the upstream directory.\n\n If allow_upstream is False and the package cannot be found\n on the sage mirrors, fall back to downloading it from\n the upstream URL if the package has one.\n ' if (not self.filename): raise ValueError('non-normal package does define a tarball, so cannot download') destination = self.upstream_fqn if os.path.isfile(destination): if self.checksum_verifies(): log.info('Using cached file {destination}'.format(destination=destination)) return else: log.warning('Invalid checksum; ignoring cached file {destination}'.format(destination=destination)) successful_download = False log.info('Attempting to download package {0} from mirrors'.format(self.filename)) for mirror in MirrorList(): url = (mirror + '/'.join(['spkg', 'upstream', self.package.name, self.filename])) log.info(url) try: Download(url, destination).run() successful_download = True break except IOError: log.debug('File not on mirror') if (not successful_download): url = self.package.tarball_upstream_url if (allow_upstream and url): log.info('Attempting to download from {}'.format(url)) try: Download(url, destination).run() successful_download = True except IOError: raise FileNotMirroredError('tarball does not exist on mirror network and neither at the upstream URL') else: raise FileNotMirroredError('tarball does not exist on mirror network') if (not self.checksum_verifies()): raise ChecksumError('checksum does not match')<|docstring|>Download the tarball to the upstream directory. If allow_upstream is False and the package cannot be found on the sage mirrors, fall back to downloading it from the upstream URL if the package has one.<|endoftext|>
e551705a0cfb0fd906a355d2c6e8d0597c3a671fd6f4449194a17cd48bd4be4a
def save_as(self, destination): '\n Save the tarball as a new file\n ' import shutil shutil.copy(self.upstream_fqn, destination)
Save the tarball as a new file
build/sage_bootstrap/tarball.py
save_as
velasjk3/SageMath
1,742
python
def save_as(self, destination): '\n \n ' import shutil shutil.copy(self.upstream_fqn, destination)
def save_as(self, destination): '\n \n ' import shutil shutil.copy(self.upstream_fqn, destination)<|docstring|>Save the tarball as a new file<|endoftext|>
c7c6b1971392dfff0b16ed4ff450ce73dba94986a7dca22cfc22cb03db824222
def test_analyze_nir(test_data): 'Test for PlantCV.' outputs.clear() img = cv2.imread(test_data.small_gray_img, (- 1)) mask = cv2.imread(test_data.small_bin_img, (- 1)) _ = analyze_nir_intensity(gray_img=img, mask=mask, bins=256, histplot=True) assert (int(outputs.observations['default']['nir_median']['value']) == 117)
Test for PlantCV.
tests/plantcv/test_analyze_nir_intensity.py
test_analyze_nir
ygarrot/plantcv
1
python
def test_analyze_nir(test_data): outputs.clear() img = cv2.imread(test_data.small_gray_img, (- 1)) mask = cv2.imread(test_data.small_bin_img, (- 1)) _ = analyze_nir_intensity(gray_img=img, mask=mask, bins=256, histplot=True) assert (int(outputs.observations['default']['nir_median']['value']) == 117)
def test_analyze_nir(test_data): outputs.clear() img = cv2.imread(test_data.small_gray_img, (- 1)) mask = cv2.imread(test_data.small_bin_img, (- 1)) _ = analyze_nir_intensity(gray_img=img, mask=mask, bins=256, histplot=True) assert (int(outputs.observations['default']['nir_median']['value']) == 117)<|docstring|>Test for PlantCV.<|endoftext|>
035456266e767e36fdf76915b73e7eb038eedf5f1d4e4e282d187e746c3fa5bf
def test_analyze_nir_16bit(test_data): 'Test for PlantCV.' outputs.clear() img = cv2.imread(test_data.small_gray_img, (- 1)) mask = cv2.imread(test_data.small_bin_img, (- 1)) _ = analyze_nir_intensity(gray_img=np.uint16(img), mask=mask, bins=256, histplot=True) assert (int(outputs.observations['default']['nir_median']['value']) == 117)
Test for PlantCV.
tests/plantcv/test_analyze_nir_intensity.py
test_analyze_nir_16bit
ygarrot/plantcv
1
python
def test_analyze_nir_16bit(test_data): outputs.clear() img = cv2.imread(test_data.small_gray_img, (- 1)) mask = cv2.imread(test_data.small_bin_img, (- 1)) _ = analyze_nir_intensity(gray_img=np.uint16(img), mask=mask, bins=256, histplot=True) assert (int(outputs.observations['default']['nir_median']['value']) == 117)
def test_analyze_nir_16bit(test_data): outputs.clear() img = cv2.imread(test_data.small_gray_img, (- 1)) mask = cv2.imread(test_data.small_bin_img, (- 1)) _ = analyze_nir_intensity(gray_img=np.uint16(img), mask=mask, bins=256, histplot=True) assert (int(outputs.observations['default']['nir_median']['value']) == 117)<|docstring|>Test for PlantCV.<|endoftext|>
89ffb4473990c464521852c4f4d1f7605a8bb3eb72884a90533d1cc101cafd7e
def __init__(self, cfg: CfgNode): '\n Initialize CSE loss from configuration options\n\n Args:\n cfg (CfgNode): configuration options\n ' self.w_segm = cfg.MODEL.ROI_DENSEPOSE_HEAD.INDEX_WEIGHTS self.w_embed = cfg.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBED_LOSS_WEIGHT self.segm_loss = MaskOrSegmentationLoss(cfg) self.embed_loss = DensePoseCseLoss.create_embed_loss(cfg)
Initialize CSE loss from configuration options Args: cfg (CfgNode): configuration options
projects/DensePose/densepose/modeling/losses/cse.py
__init__
vghost2008/detectron2
100
python
def __init__(self, cfg: CfgNode): '\n Initialize CSE loss from configuration options\n\n Args:\n cfg (CfgNode): configuration options\n ' self.w_segm = cfg.MODEL.ROI_DENSEPOSE_HEAD.INDEX_WEIGHTS self.w_embed = cfg.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBED_LOSS_WEIGHT self.segm_loss = MaskOrSegmentationLoss(cfg) self.embed_loss = DensePoseCseLoss.create_embed_loss(cfg)
def __init__(self, cfg: CfgNode): '\n Initialize CSE loss from configuration options\n\n Args:\n cfg (CfgNode): configuration options\n ' self.w_segm = cfg.MODEL.ROI_DENSEPOSE_HEAD.INDEX_WEIGHTS self.w_embed = cfg.MODEL.ROI_DENSEPOSE_HEAD.CSE.EMBED_LOSS_WEIGHT self.segm_loss = MaskOrSegmentationLoss(cfg) self.embed_loss = DensePoseCseLoss.create_embed_loss(cfg)<|docstring|>Initialize CSE loss from configuration options Args: cfg (CfgNode): configuration options<|endoftext|>
964ce90cad23a97a1446de497b75f10d6fa678c12e20d279637b0c1fa9de9f74
def _validate_variable(self, variable, context=None): 'Validates that variable is 1d array\n ' if (len(np.atleast_2d(variable)) != 1): raise FunctionError('Variable for {} must contain a single array or list of numbers'.format(self.name)) return variable
Validates that variable is 1d array
psyneulink/core/components/functions/nonstateful/objectivefunctions.py
_validate_variable
MetaCell/PsyNeuLink
67
python
def _validate_variable(self, variable, context=None): '\n ' if (len(np.atleast_2d(variable)) != 1): raise FunctionError('Variable for {} must contain a single array or list of numbers'.format(self.name)) return variable
def _validate_variable(self, variable, context=None): '\n ' if (len(np.atleast_2d(variable)) != 1): raise FunctionError('Variable for {} must contain a single array or list of numbers'.format(self.name)) return variable<|docstring|>Validates that variable is 1d array<|endoftext|>
8d654c8582b7dbde19a490af1a4bde0fc5860b4ceeea0e74fedbcd663ed1dc27
def _validate_params(self, variable, request_set, target_set=None, context=None): 'Validate matrix param\n\n `matrix <Stability.matrix>` argument must be one of the following\n - 2d list, np.ndarray or np.matrix\n - ParameterPort for one of the above\n - MappingProjection with a parameterPorts[MATRIX] for one of the above\n\n Parse matrix specification to insure it resolves to a square matrix\n (but leave in the form in which it was specified so that, if it is a ParameterPort or MappingProjection,\n its current value can be accessed at runtime (i.e., it can be used as a "pointer")\n ' if ((MATRIX in target_set) and (not isinstance(target_set[MATRIX], str))): from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection from psyneulink.core.components.ports.parameterport import ParameterPort matrix = target_set[MATRIX] if isinstance(matrix, MappingProjection): try: matrix = matrix._parameter_ports[MATRIX].value param_type_string = "MappingProjection's ParameterPort" except KeyError: raise FunctionError('The MappingProjection specified for the {} arg of {} ({}) must have a {} ParameterPort that has been assigned a 2d array or matrix'.format(MATRIX, self.name, matrix.shape, MATRIX)) elif isinstance(matrix, ParameterPort): try: matrix = matrix.value param_type_string = 'ParameterPort' except KeyError: raise FunctionError('The value of the {} parameterPort specified for the {} arg of {} ({}) must be a 2d array or matrix'.format(MATRIX, MATRIX, self.name, matrix.shape)) else: param_type_string = 'array or matrix' matrix = np.array(matrix) if (matrix.ndim != 2): raise FunctionError('The value of the {} specified for the {} arg of {} ({}) must be a 2d array or matrix'.format(param_type_string, MATRIX, self.name, matrix)) rows = matrix.shape[0] cols = matrix.shape[1] squeezed = np.array(self.defaults.variable) if (squeezed.ndim > 1): squeezed = np.squeeze(squeezed) size = safe_len(squeezed) if (rows != size): raise FunctionError('The value of the {} specified for the {} arg of {} is the wrong size;it is {}x{}, but must be square matrix of size {}'.format(param_type_string, MATRIX, self.name, rows, cols, size)) if (rows != cols): raise FunctionError('The value of the {} specified for the {} arg of {} ({}) must be a square matrix'.format(param_type_string, MATRIX, self.name, matrix)) super()._validate_params(request_set=request_set, target_set=target_set, context=context)
Validate matrix param `matrix <Stability.matrix>` argument must be one of the following - 2d list, np.ndarray or np.matrix - ParameterPort for one of the above - MappingProjection with a parameterPorts[MATRIX] for one of the above Parse matrix specification to insure it resolves to a square matrix (but leave in the form in which it was specified so that, if it is a ParameterPort or MappingProjection, its current value can be accessed at runtime (i.e., it can be used as a "pointer")
psyneulink/core/components/functions/nonstateful/objectivefunctions.py
_validate_params
MetaCell/PsyNeuLink
67
python
def _validate_params(self, variable, request_set, target_set=None, context=None): 'Validate matrix param\n\n `matrix <Stability.matrix>` argument must be one of the following\n - 2d list, np.ndarray or np.matrix\n - ParameterPort for one of the above\n - MappingProjection with a parameterPorts[MATRIX] for one of the above\n\n Parse matrix specification to insure it resolves to a square matrix\n (but leave in the form in which it was specified so that, if it is a ParameterPort or MappingProjection,\n its current value can be accessed at runtime (i.e., it can be used as a "pointer")\n ' if ((MATRIX in target_set) and (not isinstance(target_set[MATRIX], str))): from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection from psyneulink.core.components.ports.parameterport import ParameterPort matrix = target_set[MATRIX] if isinstance(matrix, MappingProjection): try: matrix = matrix._parameter_ports[MATRIX].value param_type_string = "MappingProjection's ParameterPort" except KeyError: raise FunctionError('The MappingProjection specified for the {} arg of {} ({}) must have a {} ParameterPort that has been assigned a 2d array or matrix'.format(MATRIX, self.name, matrix.shape, MATRIX)) elif isinstance(matrix, ParameterPort): try: matrix = matrix.value param_type_string = 'ParameterPort' except KeyError: raise FunctionError('The value of the {} parameterPort specified for the {} arg of {} ({}) must be a 2d array or matrix'.format(MATRIX, MATRIX, self.name, matrix.shape)) else: param_type_string = 'array or matrix' matrix = np.array(matrix) if (matrix.ndim != 2): raise FunctionError('The value of the {} specified for the {} arg of {} ({}) must be a 2d array or matrix'.format(param_type_string, MATRIX, self.name, matrix)) rows = matrix.shape[0] cols = matrix.shape[1] squeezed = np.array(self.defaults.variable) if (squeezed.ndim > 1): squeezed = np.squeeze(squeezed) size = safe_len(squeezed) if (rows != size): raise FunctionError('The value of the {} specified for the {} arg of {} is the wrong size;it is {}x{}, but must be square matrix of size {}'.format(param_type_string, MATRIX, self.name, rows, cols, size)) if (rows != cols): raise FunctionError('The value of the {} specified for the {} arg of {} ({}) must be a square matrix'.format(param_type_string, MATRIX, self.name, matrix)) super()._validate_params(request_set=request_set, target_set=target_set, context=context)
def _validate_params(self, variable, request_set, target_set=None, context=None): 'Validate matrix param\n\n `matrix <Stability.matrix>` argument must be one of the following\n - 2d list, np.ndarray or np.matrix\n - ParameterPort for one of the above\n - MappingProjection with a parameterPorts[MATRIX] for one of the above\n\n Parse matrix specification to insure it resolves to a square matrix\n (but leave in the form in which it was specified so that, if it is a ParameterPort or MappingProjection,\n its current value can be accessed at runtime (i.e., it can be used as a "pointer")\n ' if ((MATRIX in target_set) and (not isinstance(target_set[MATRIX], str))): from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection from psyneulink.core.components.ports.parameterport import ParameterPort matrix = target_set[MATRIX] if isinstance(matrix, MappingProjection): try: matrix = matrix._parameter_ports[MATRIX].value param_type_string = "MappingProjection's ParameterPort" except KeyError: raise FunctionError('The MappingProjection specified for the {} arg of {} ({}) must have a {} ParameterPort that has been assigned a 2d array or matrix'.format(MATRIX, self.name, matrix.shape, MATRIX)) elif isinstance(matrix, ParameterPort): try: matrix = matrix.value param_type_string = 'ParameterPort' except KeyError: raise FunctionError('The value of the {} parameterPort specified for the {} arg of {} ({}) must be a 2d array or matrix'.format(MATRIX, MATRIX, self.name, matrix.shape)) else: param_type_string = 'array or matrix' matrix = np.array(matrix) if (matrix.ndim != 2): raise FunctionError('The value of the {} specified for the {} arg of {} ({}) must be a 2d array or matrix'.format(param_type_string, MATRIX, self.name, matrix)) rows = matrix.shape[0] cols = matrix.shape[1] squeezed = np.array(self.defaults.variable) if (squeezed.ndim > 1): squeezed = np.squeeze(squeezed) size = safe_len(squeezed) if (rows != size): raise FunctionError('The value of the {} specified for the {} arg of {} is the wrong size;it is {}x{}, but must be square matrix of size {}'.format(param_type_string, MATRIX, self.name, rows, cols, size)) if (rows != cols): raise FunctionError('The value of the {} specified for the {} arg of {} ({}) must be a square matrix'.format(param_type_string, MATRIX, self.name, matrix)) super()._validate_params(request_set=request_set, target_set=target_set, context=context)<|docstring|>Validate matrix param `matrix <Stability.matrix>` argument must be one of the following - 2d list, np.ndarray or np.matrix - ParameterPort for one of the above - MappingProjection with a parameterPorts[MATRIX] for one of the above Parse matrix specification to insure it resolves to a square matrix (but leave in the form in which it was specified so that, if it is a ParameterPort or MappingProjection, its current value can be accessed at runtime (i.e., it can be used as a "pointer")<|endoftext|>
d45dcb61d4c5f246cc212ea411e287884fb92afb91c84dbb1d64a20203d5d4f1
def _instantiate_attributes_before_function(self, function=None, context=None): 'Instantiate matrix\n\n Specified matrix is convolved with HOLLOW_MATRIX\n to eliminate the diagonal (self-connections) from the calculation.\n The `Distance` Function is used for all calculations except ENERGY (which is not really a distance metric).\n If ENTROPY is specified as the metric, convert to CROSS_ENTROPY for use with the Distance Function.\n :param function:\n\n ' from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection from psyneulink.core.components.ports.parameterport import ParameterPort squeezed = np.array(self.defaults.variable) if (squeezed.ndim > 1): squeezed = np.squeeze(squeezed) size = safe_len(squeezed) matrix = self.parameters.matrix._get(context) if isinstance(matrix, MappingProjection): matrix = matrix._parameter_ports[MATRIX] elif isinstance(matrix, ParameterPort): pass else: matrix = get_matrix(matrix, size, size) self.parameters.matrix._set(matrix, context) self._hollow_matrix = get_matrix(HOLLOW_MATRIX, size, size) default_variable = [self.defaults.variable, self.defaults.variable] if (self.metric == ENTROPY): self.metric_fct = Distance(default_variable=default_variable, metric=CROSS_ENTROPY, normalize=self.normalize) elif (self.metric in DISTANCE_METRICS._set()): self.metric_fct = Distance(default_variable=default_variable, metric=self.metric, normalize=self.normalize) else: assert False, 'Unknown metric' self.parameters.metric_fct.set(self.metric_fct)
Instantiate matrix Specified matrix is convolved with HOLLOW_MATRIX to eliminate the diagonal (self-connections) from the calculation. The `Distance` Function is used for all calculations except ENERGY (which is not really a distance metric). If ENTROPY is specified as the metric, convert to CROSS_ENTROPY for use with the Distance Function. :param function:
psyneulink/core/components/functions/nonstateful/objectivefunctions.py
_instantiate_attributes_before_function
MetaCell/PsyNeuLink
67
python
def _instantiate_attributes_before_function(self, function=None, context=None): 'Instantiate matrix\n\n Specified matrix is convolved with HOLLOW_MATRIX\n to eliminate the diagonal (self-connections) from the calculation.\n The `Distance` Function is used for all calculations except ENERGY (which is not really a distance metric).\n If ENTROPY is specified as the metric, convert to CROSS_ENTROPY for use with the Distance Function.\n :param function:\n\n ' from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection from psyneulink.core.components.ports.parameterport import ParameterPort squeezed = np.array(self.defaults.variable) if (squeezed.ndim > 1): squeezed = np.squeeze(squeezed) size = safe_len(squeezed) matrix = self.parameters.matrix._get(context) if isinstance(matrix, MappingProjection): matrix = matrix._parameter_ports[MATRIX] elif isinstance(matrix, ParameterPort): pass else: matrix = get_matrix(matrix, size, size) self.parameters.matrix._set(matrix, context) self._hollow_matrix = get_matrix(HOLLOW_MATRIX, size, size) default_variable = [self.defaults.variable, self.defaults.variable] if (self.metric == ENTROPY): self.metric_fct = Distance(default_variable=default_variable, metric=CROSS_ENTROPY, normalize=self.normalize) elif (self.metric in DISTANCE_METRICS._set()): self.metric_fct = Distance(default_variable=default_variable, metric=self.metric, normalize=self.normalize) else: assert False, 'Unknown metric' self.parameters.metric_fct.set(self.metric_fct)
def _instantiate_attributes_before_function(self, function=None, context=None): 'Instantiate matrix\n\n Specified matrix is convolved with HOLLOW_MATRIX\n to eliminate the diagonal (self-connections) from the calculation.\n The `Distance` Function is used for all calculations except ENERGY (which is not really a distance metric).\n If ENTROPY is specified as the metric, convert to CROSS_ENTROPY for use with the Distance Function.\n :param function:\n\n ' from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection from psyneulink.core.components.ports.parameterport import ParameterPort squeezed = np.array(self.defaults.variable) if (squeezed.ndim > 1): squeezed = np.squeeze(squeezed) size = safe_len(squeezed) matrix = self.parameters.matrix._get(context) if isinstance(matrix, MappingProjection): matrix = matrix._parameter_ports[MATRIX] elif isinstance(matrix, ParameterPort): pass else: matrix = get_matrix(matrix, size, size) self.parameters.matrix._set(matrix, context) self._hollow_matrix = get_matrix(HOLLOW_MATRIX, size, size) default_variable = [self.defaults.variable, self.defaults.variable] if (self.metric == ENTROPY): self.metric_fct = Distance(default_variable=default_variable, metric=CROSS_ENTROPY, normalize=self.normalize) elif (self.metric in DISTANCE_METRICS._set()): self.metric_fct = Distance(default_variable=default_variable, metric=self.metric, normalize=self.normalize) else: assert False, 'Unknown metric' self.parameters.metric_fct.set(self.metric_fct)<|docstring|>Instantiate matrix Specified matrix is convolved with HOLLOW_MATRIX to eliminate the diagonal (self-connections) from the calculation. The `Distance` Function is used for all calculations except ENERGY (which is not really a distance metric). If ENTROPY is specified as the metric, convert to CROSS_ENTROPY for use with the Distance Function. :param function:<|endoftext|>
63e5af873f4a66e6c3b9f492e17b1bc15e5b2c3865294b7df977acf969977d29
def _function(self, variable=None, context=None, params=None): 'Calculate the stability of `variable <Stability.variable>`.\n\n Compare the value of `variable <Stability.variable>` with its value after transformation by\n `matrix <Stability.matrix>` and `transfer_fct <Stability.transfer_fct>` (if specified), using the specified\n `metric <Stability.metric>`. If `normalize <Stability.normalize>` is `True`, the result is divided\n by the length of `variable <Stability.variable>`.\n\n Returns\n -------\n\n stability : scalar\n\n ' variable = np.array(variable) if (variable.ndim > 1): variable = np.squeeze(variable) matrix = self._get_current_parameter_value(MATRIX, context) current = variable transformed = np.dot((matrix * self._hollow_matrix), variable) if (self.transfer_fct is not None): transformed = self.transfer_fct(transformed) result = self.metric_fct(variable=[current, transformed], context=context) return self.convert_output_type(result)
Calculate the stability of `variable <Stability.variable>`. Compare the value of `variable <Stability.variable>` with its value after transformation by `matrix <Stability.matrix>` and `transfer_fct <Stability.transfer_fct>` (if specified), using the specified `metric <Stability.metric>`. If `normalize <Stability.normalize>` is `True`, the result is divided by the length of `variable <Stability.variable>`. Returns ------- stability : scalar
psyneulink/core/components/functions/nonstateful/objectivefunctions.py
_function
MetaCell/PsyNeuLink
67
python
def _function(self, variable=None, context=None, params=None): 'Calculate the stability of `variable <Stability.variable>`.\n\n Compare the value of `variable <Stability.variable>` with its value after transformation by\n `matrix <Stability.matrix>` and `transfer_fct <Stability.transfer_fct>` (if specified), using the specified\n `metric <Stability.metric>`. If `normalize <Stability.normalize>` is `True`, the result is divided\n by the length of `variable <Stability.variable>`.\n\n Returns\n -------\n\n stability : scalar\n\n ' variable = np.array(variable) if (variable.ndim > 1): variable = np.squeeze(variable) matrix = self._get_current_parameter_value(MATRIX, context) current = variable transformed = np.dot((matrix * self._hollow_matrix), variable) if (self.transfer_fct is not None): transformed = self.transfer_fct(transformed) result = self.metric_fct(variable=[current, transformed], context=context) return self.convert_output_type(result)
def _function(self, variable=None, context=None, params=None): 'Calculate the stability of `variable <Stability.variable>`.\n\n Compare the value of `variable <Stability.variable>` with its value after transformation by\n `matrix <Stability.matrix>` and `transfer_fct <Stability.transfer_fct>` (if specified), using the specified\n `metric <Stability.metric>`. If `normalize <Stability.normalize>` is `True`, the result is divided\n by the length of `variable <Stability.variable>`.\n\n Returns\n -------\n\n stability : scalar\n\n ' variable = np.array(variable) if (variable.ndim > 1): variable = np.squeeze(variable) matrix = self._get_current_parameter_value(MATRIX, context) current = variable transformed = np.dot((matrix * self._hollow_matrix), variable) if (self.transfer_fct is not None): transformed = self.transfer_fct(transformed) result = self.metric_fct(variable=[current, transformed], context=context) return self.convert_output_type(result)<|docstring|>Calculate the stability of `variable <Stability.variable>`. Compare the value of `variable <Stability.variable>` with its value after transformation by `matrix <Stability.matrix>` and `transfer_fct <Stability.transfer_fct>` (if specified), using the specified `metric <Stability.metric>`. If `normalize <Stability.normalize>` is `True`, the result is divided by the length of `variable <Stability.variable>`. Returns ------- stability : scalar<|endoftext|>
cccd5c535e5ee334501f3bf1bea16d87ee5666712a17d5f5eacbce2a840079b8
def _validate_params(self, request_set, target_set=None, variable=None, context=None): 'Validate that variable has two items of equal length\n\n ' super()._validate_params(request_set=request_set, target_set=target_set, context=context) err_two_items = FunctionError('variable for {} ({}) must have two items'.format(self.name, variable)) try: if (len(variable) != 2): raise err_two_items except TypeError: raise err_two_items try: if (len(variable[0]) != len(variable[1])): raise FunctionError('The lengths of the items in the variable for {0} ({1},{2}) must be equal'.format(self.name, variable[0], variable[1])) except TypeError: if (is_iterable(variable[0]) ^ is_iterable(variable[1])): raise FunctionError('The lengths of the items in the variable for {0} ({1},{2}) must be equal'.format(self.name, variable[0], variable[1]))
Validate that variable has two items of equal length
psyneulink/core/components/functions/nonstateful/objectivefunctions.py
_validate_params
MetaCell/PsyNeuLink
67
python
def _validate_params(self, request_set, target_set=None, variable=None, context=None): '\n\n ' super()._validate_params(request_set=request_set, target_set=target_set, context=context) err_two_items = FunctionError('variable for {} ({}) must have two items'.format(self.name, variable)) try: if (len(variable) != 2): raise err_two_items except TypeError: raise err_two_items try: if (len(variable[0]) != len(variable[1])): raise FunctionError('The lengths of the items in the variable for {0} ({1},{2}) must be equal'.format(self.name, variable[0], variable[1])) except TypeError: if (is_iterable(variable[0]) ^ is_iterable(variable[1])): raise FunctionError('The lengths of the items in the variable for {0} ({1},{2}) must be equal'.format(self.name, variable[0], variable[1]))
def _validate_params(self, request_set, target_set=None, variable=None, context=None): '\n\n ' super()._validate_params(request_set=request_set, target_set=target_set, context=context) err_two_items = FunctionError('variable for {} ({}) must have two items'.format(self.name, variable)) try: if (len(variable) != 2): raise err_two_items except TypeError: raise err_two_items try: if (len(variable[0]) != len(variable[1])): raise FunctionError('The lengths of the items in the variable for {0} ({1},{2}) must be equal'.format(self.name, variable[0], variable[1])) except TypeError: if (is_iterable(variable[0]) ^ is_iterable(variable[1])): raise FunctionError('The lengths of the items in the variable for {0} ({1},{2}) must be equal'.format(self.name, variable[0], variable[1]))<|docstring|>Validate that variable has two items of equal length<|endoftext|>
712a4b108cdcaed174f1e2cafeaa17f658aee87045929fdfc88a8be4458ca518
def _function(self, variable=None, context=None, params=None): 'Calculate the distance between the two vectors in `variable <Stability.variable>`.\n\n Use the `distance metric <DistanceMetrics>` specified in `metric <Distance.metric>` to calculate the distance.\n If `normalize <Distance.normalize>` is `True`, the result is divided by the length of `variable\n <Distance.variable>`.\n\n Returns\n -------\n\n distance : scalar\n\n ' try: v1 = np.hstack(variable[0]) except TypeError: v1 = variable[0] try: v2 = np.hstack(variable[1]) except TypeError: v2 = variable[1] if (self.metric == MAX_ABS_DIFF): result = np.max(np.fabs((v1 - v2))) elif (self.metric == DIFFERENCE): result = np.sum(np.fabs((v1 - v2))) elif (self.metric == NORMED_L0_SIMILARITY): result = (1.0 - (np.sum(np.abs((v1 - v2))) / 4.0)) elif (self.metric == EUCLIDEAN): result = np.linalg.norm((v2 - v1)) elif (self.metric == COSINE): result = (1.0 - np.fabs(Distance.cosine(v1, v2))) return self.convert_output_type(result) elif (self.metric == CORRELATION): result = (1.0 - np.fabs(Distance.correlation(v1, v2))) return self.convert_output_type(result) elif (self.metric == CROSS_ENTROPY): if (not self.is_initializing): v1 = np.where((v1 == 0), EPSILON, v1) v2 = np.where((v2 == 0), EPSILON, v2) result = (- np.sum(np.where(np.logical_and((v1 == 0), (v2 == 0)), 0.0, (v1 * np.log(v2))))) elif (self.metric == ENERGY): result = ((- np.sum((v1 * v2))) / 2.0) else: assert False, '{} not a recognized metric in {}'.format(self.metric, self.__class__.__name__) if (self.normalize and (self.metric not in {MAX_ABS_DIFF, CORRELATION})): if (self.metric == ENERGY): result /= (len(v1) ** 2.0) else: result /= len(v1) return self.convert_output_type(result)
Calculate the distance between the two vectors in `variable <Stability.variable>`. Use the `distance metric <DistanceMetrics>` specified in `metric <Distance.metric>` to calculate the distance. If `normalize <Distance.normalize>` is `True`, the result is divided by the length of `variable <Distance.variable>`. Returns ------- distance : scalar
psyneulink/core/components/functions/nonstateful/objectivefunctions.py
_function
MetaCell/PsyNeuLink
67
python
def _function(self, variable=None, context=None, params=None): 'Calculate the distance between the two vectors in `variable <Stability.variable>`.\n\n Use the `distance metric <DistanceMetrics>` specified in `metric <Distance.metric>` to calculate the distance.\n If `normalize <Distance.normalize>` is `True`, the result is divided by the length of `variable\n <Distance.variable>`.\n\n Returns\n -------\n\n distance : scalar\n\n ' try: v1 = np.hstack(variable[0]) except TypeError: v1 = variable[0] try: v2 = np.hstack(variable[1]) except TypeError: v2 = variable[1] if (self.metric == MAX_ABS_DIFF): result = np.max(np.fabs((v1 - v2))) elif (self.metric == DIFFERENCE): result = np.sum(np.fabs((v1 - v2))) elif (self.metric == NORMED_L0_SIMILARITY): result = (1.0 - (np.sum(np.abs((v1 - v2))) / 4.0)) elif (self.metric == EUCLIDEAN): result = np.linalg.norm((v2 - v1)) elif (self.metric == COSINE): result = (1.0 - np.fabs(Distance.cosine(v1, v2))) return self.convert_output_type(result) elif (self.metric == CORRELATION): result = (1.0 - np.fabs(Distance.correlation(v1, v2))) return self.convert_output_type(result) elif (self.metric == CROSS_ENTROPY): if (not self.is_initializing): v1 = np.where((v1 == 0), EPSILON, v1) v2 = np.where((v2 == 0), EPSILON, v2) result = (- np.sum(np.where(np.logical_and((v1 == 0), (v2 == 0)), 0.0, (v1 * np.log(v2))))) elif (self.metric == ENERGY): result = ((- np.sum((v1 * v2))) / 2.0) else: assert False, '{} not a recognized metric in {}'.format(self.metric, self.__class__.__name__) if (self.normalize and (self.metric not in {MAX_ABS_DIFF, CORRELATION})): if (self.metric == ENERGY): result /= (len(v1) ** 2.0) else: result /= len(v1) return self.convert_output_type(result)
def _function(self, variable=None, context=None, params=None): 'Calculate the distance between the two vectors in `variable <Stability.variable>`.\n\n Use the `distance metric <DistanceMetrics>` specified in `metric <Distance.metric>` to calculate the distance.\n If `normalize <Distance.normalize>` is `True`, the result is divided by the length of `variable\n <Distance.variable>`.\n\n Returns\n -------\n\n distance : scalar\n\n ' try: v1 = np.hstack(variable[0]) except TypeError: v1 = variable[0] try: v2 = np.hstack(variable[1]) except TypeError: v2 = variable[1] if (self.metric == MAX_ABS_DIFF): result = np.max(np.fabs((v1 - v2))) elif (self.metric == DIFFERENCE): result = np.sum(np.fabs((v1 - v2))) elif (self.metric == NORMED_L0_SIMILARITY): result = (1.0 - (np.sum(np.abs((v1 - v2))) / 4.0)) elif (self.metric == EUCLIDEAN): result = np.linalg.norm((v2 - v1)) elif (self.metric == COSINE): result = (1.0 - np.fabs(Distance.cosine(v1, v2))) return self.convert_output_type(result) elif (self.metric == CORRELATION): result = (1.0 - np.fabs(Distance.correlation(v1, v2))) return self.convert_output_type(result) elif (self.metric == CROSS_ENTROPY): if (not self.is_initializing): v1 = np.where((v1 == 0), EPSILON, v1) v2 = np.where((v2 == 0), EPSILON, v2) result = (- np.sum(np.where(np.logical_and((v1 == 0), (v2 == 0)), 0.0, (v1 * np.log(v2))))) elif (self.metric == ENERGY): result = ((- np.sum((v1 * v2))) / 2.0) else: assert False, '{} not a recognized metric in {}'.format(self.metric, self.__class__.__name__) if (self.normalize and (self.metric not in {MAX_ABS_DIFF, CORRELATION})): if (self.metric == ENERGY): result /= (len(v1) ** 2.0) else: result /= len(v1) return self.convert_output_type(result)<|docstring|>Calculate the distance between the two vectors in `variable <Stability.variable>`. Use the `distance metric <DistanceMetrics>` specified in `metric <Distance.metric>` to calculate the distance. If `normalize <Distance.normalize>` is `True`, the result is divided by the length of `variable <Distance.variable>`. Returns ------- distance : scalar<|endoftext|>
cfd5220fbf9ff5f4973151b0b0e49dbf98ba3961c304d72a86f3e6c5bd035c5f
def filter_queryset(self, qs, filter_param): '\n Filter the queryset `qs`, given the selected `filter_param`. Default\n implementation does no filtering at all.\n ' return qs
Filter the queryset `qs`, given the selected `filter_param`. Default implementation does no filtering at all.
src/mds/web/generic/filtering.py
filter_queryset
m-socha/sana.mds
2
python
def filter_queryset(self, qs, filter_param): '\n Filter the queryset `qs`, given the selected `filter_param`. Default\n implementation does no filtering at all.\n ' return qs
def filter_queryset(self, qs, filter_param): '\n Filter the queryset `qs`, given the selected `filter_param`. Default\n implementation does no filtering at all.\n ' return qs<|docstring|>Filter the queryset `qs`, given the selected `filter_param`. Default implementation does no filtering at all.<|endoftext|>
5419dd55e01e938e839d1771850f83fb88f2397ebf52c2ba58f3c31bc7abf5da
def handle(self, *args, **options): 'See :meth:`django.core.management.base.BaseCommand.handle`.\n\n This method starts the Scale daily metrics.\n ' day = options.get('day') logger.info('Command starting: scale_daily_metrics') logger.info(' - Day: %s', day) logger.info('Generating metrics...') date = datetime.datetime.strptime(day, '%Y-%m-%d') failed = 0 for provider in registry.get_providers(): metrics_type = provider.get_metrics_type() try: logger.info('Starting: %s', metrics_type.name) self._calculate_metrics(provider, date) logger.info('Completed: %s', metrics_type.name) except: failed += 1 logger.exception('Unable to calculate metrics: %s', metrics_type.name) logger.info('Command completed: scale_daily_metrics') if failed: logger.info('Metric providers failed: %i', failed) sys.exit(failed)
See :meth:`django.core.management.base.BaseCommand.handle`. This method starts the Scale daily metrics.
scale/metrics/management/commands/scale_daily_metrics.py
handle
kfconsultant/scale
121
python
def handle(self, *args, **options): 'See :meth:`django.core.management.base.BaseCommand.handle`.\n\n This method starts the Scale daily metrics.\n ' day = options.get('day') logger.info('Command starting: scale_daily_metrics') logger.info(' - Day: %s', day) logger.info('Generating metrics...') date = datetime.datetime.strptime(day, '%Y-%m-%d') failed = 0 for provider in registry.get_providers(): metrics_type = provider.get_metrics_type() try: logger.info('Starting: %s', metrics_type.name) self._calculate_metrics(provider, date) logger.info('Completed: %s', metrics_type.name) except: failed += 1 logger.exception('Unable to calculate metrics: %s', metrics_type.name) logger.info('Command completed: scale_daily_metrics') if failed: logger.info('Metric providers failed: %i', failed) sys.exit(failed)
def handle(self, *args, **options): 'See :meth:`django.core.management.base.BaseCommand.handle`.\n\n This method starts the Scale daily metrics.\n ' day = options.get('day') logger.info('Command starting: scale_daily_metrics') logger.info(' - Day: %s', day) logger.info('Generating metrics...') date = datetime.datetime.strptime(day, '%Y-%m-%d') failed = 0 for provider in registry.get_providers(): metrics_type = provider.get_metrics_type() try: logger.info('Starting: %s', metrics_type.name) self._calculate_metrics(provider, date) logger.info('Completed: %s', metrics_type.name) except: failed += 1 logger.exception('Unable to calculate metrics: %s', metrics_type.name) logger.info('Command completed: scale_daily_metrics') if failed: logger.info('Metric providers failed: %i', failed) sys.exit(failed)<|docstring|>See :meth:`django.core.management.base.BaseCommand.handle`. This method starts the Scale daily metrics.<|endoftext|>
997d3e685142ee466ff9327586a077cbdb5ad0ec2c9b68202a91eeaace940cbb
@retry_database_query def _calculate_metrics(self, provider, date): 'Calculates the Scale metrics for the given date with the given provider\n\n :param provider: The metrics provider\n :type provider: :class:`metrics.registry.MetricsTypeProvider`\n :param date: The date for generating metrics\n :type date: :class:`datetime.datetime`\n ' provider.calculate(date)
Calculates the Scale metrics for the given date with the given provider :param provider: The metrics provider :type provider: :class:`metrics.registry.MetricsTypeProvider` :param date: The date for generating metrics :type date: :class:`datetime.datetime`
scale/metrics/management/commands/scale_daily_metrics.py
_calculate_metrics
kfconsultant/scale
121
python
@retry_database_query def _calculate_metrics(self, provider, date): 'Calculates the Scale metrics for the given date with the given provider\n\n :param provider: The metrics provider\n :type provider: :class:`metrics.registry.MetricsTypeProvider`\n :param date: The date for generating metrics\n :type date: :class:`datetime.datetime`\n ' provider.calculate(date)
@retry_database_query def _calculate_metrics(self, provider, date): 'Calculates the Scale metrics for the given date with the given provider\n\n :param provider: The metrics provider\n :type provider: :class:`metrics.registry.MetricsTypeProvider`\n :param date: The date for generating metrics\n :type date: :class:`datetime.datetime`\n ' provider.calculate(date)<|docstring|>Calculates the Scale metrics for the given date with the given provider :param provider: The metrics provider :type provider: :class:`metrics.registry.MetricsTypeProvider` :param date: The date for generating metrics :type date: :class:`datetime.datetime`<|endoftext|>
d727af41d28527ea93007af3bb3af31c14a4ff7a0ac57901ce90253c7718a98a
@abc.abstractmethod def belongs(self, point, atol=gs.atol): 'Evaluate if a point belongs to the manifold.\n\n Parameters\n ----------\n point : array-like, shape=[..., dim]\n Point to evaluate.\n atol : float\n Absolute tolerance.\n Optional, default: backend atol.\n\n Returns\n -------\n belongs : array-like, shape=[...,]\n Boolean evaluating if point belongs to the manifold.\n '
Evaluate if a point belongs to the manifold. Parameters ---------- point : array-like, shape=[..., dim] Point to evaluate. atol : float Absolute tolerance. Optional, default: backend atol. Returns ------- belongs : array-like, shape=[...,] Boolean evaluating if point belongs to the manifold.
geomstats/geometry/manifold.py
belongs
qbarthelemy/geomstats
743
python
@abc.abstractmethod def belongs(self, point, atol=gs.atol): 'Evaluate if a point belongs to the manifold.\n\n Parameters\n ----------\n point : array-like, shape=[..., dim]\n Point to evaluate.\n atol : float\n Absolute tolerance.\n Optional, default: backend atol.\n\n Returns\n -------\n belongs : array-like, shape=[...,]\n Boolean evaluating if point belongs to the manifold.\n '
@abc.abstractmethod def belongs(self, point, atol=gs.atol): 'Evaluate if a point belongs to the manifold.\n\n Parameters\n ----------\n point : array-like, shape=[..., dim]\n Point to evaluate.\n atol : float\n Absolute tolerance.\n Optional, default: backend atol.\n\n Returns\n -------\n belongs : array-like, shape=[...,]\n Boolean evaluating if point belongs to the manifold.\n '<|docstring|>Evaluate if a point belongs to the manifold. Parameters ---------- point : array-like, shape=[..., dim] Point to evaluate. atol : float Absolute tolerance. Optional, default: backend atol. Returns ------- belongs : array-like, shape=[...,] Boolean evaluating if point belongs to the manifold.<|endoftext|>
6c43639b9dd16f96e368e859b97937f686e02e1f806e44b4f05f34944855d0c4
@abc.abstractmethod def is_tangent(self, vector, base_point, atol=gs.atol): 'Check whether the vector is tangent at base_point.\n\n Parameters\n ----------\n vector : array-like, shape=[..., dim]\n Vector.\n base_point : array-like, shape=[..., dim]\n Point on the manifold.\n atol : float\n Absolute tolerance.\n Optional, default: backend atol.\n\n Returns\n -------\n is_tangent : bool\n Boolean denoting if vector is a tangent vector at the base point.\n '
Check whether the vector is tangent at base_point. Parameters ---------- vector : array-like, shape=[..., dim] Vector. base_point : array-like, shape=[..., dim] Point on the manifold. atol : float Absolute tolerance. Optional, default: backend atol. Returns ------- is_tangent : bool Boolean denoting if vector is a tangent vector at the base point.
geomstats/geometry/manifold.py
is_tangent
qbarthelemy/geomstats
743
python
@abc.abstractmethod def is_tangent(self, vector, base_point, atol=gs.atol): 'Check whether the vector is tangent at base_point.\n\n Parameters\n ----------\n vector : array-like, shape=[..., dim]\n Vector.\n base_point : array-like, shape=[..., dim]\n Point on the manifold.\n atol : float\n Absolute tolerance.\n Optional, default: backend atol.\n\n Returns\n -------\n is_tangent : bool\n Boolean denoting if vector is a tangent vector at the base point.\n '
@abc.abstractmethod def is_tangent(self, vector, base_point, atol=gs.atol): 'Check whether the vector is tangent at base_point.\n\n Parameters\n ----------\n vector : array-like, shape=[..., dim]\n Vector.\n base_point : array-like, shape=[..., dim]\n Point on the manifold.\n atol : float\n Absolute tolerance.\n Optional, default: backend atol.\n\n Returns\n -------\n is_tangent : bool\n Boolean denoting if vector is a tangent vector at the base point.\n '<|docstring|>Check whether the vector is tangent at base_point. Parameters ---------- vector : array-like, shape=[..., dim] Vector. base_point : array-like, shape=[..., dim] Point on the manifold. atol : float Absolute tolerance. Optional, default: backend atol. Returns ------- is_tangent : bool Boolean denoting if vector is a tangent vector at the base point.<|endoftext|>
ba0f2f68e429f6f25552558799fc863825fca809732fc433fb3d64f9de3d967e
@abc.abstractmethod def to_tangent(self, vector, base_point): 'Project a vector to a tangent space of the manifold.\n\n Parameters\n ----------\n vector : array-like, shape=[..., dim]\n Vector.\n base_point : array-like, shape=[..., dim]\n Point on the manifold.\n\n Returns\n -------\n tangent_vec : array-like, shape=[..., dim]\n Tangent vector at base point.\n '
Project a vector to a tangent space of the manifold. Parameters ---------- vector : array-like, shape=[..., dim] Vector. base_point : array-like, shape=[..., dim] Point on the manifold. Returns ------- tangent_vec : array-like, shape=[..., dim] Tangent vector at base point.
geomstats/geometry/manifold.py
to_tangent
qbarthelemy/geomstats
743
python
@abc.abstractmethod def to_tangent(self, vector, base_point): 'Project a vector to a tangent space of the manifold.\n\n Parameters\n ----------\n vector : array-like, shape=[..., dim]\n Vector.\n base_point : array-like, shape=[..., dim]\n Point on the manifold.\n\n Returns\n -------\n tangent_vec : array-like, shape=[..., dim]\n Tangent vector at base point.\n '
@abc.abstractmethod def to_tangent(self, vector, base_point): 'Project a vector to a tangent space of the manifold.\n\n Parameters\n ----------\n vector : array-like, shape=[..., dim]\n Vector.\n base_point : array-like, shape=[..., dim]\n Point on the manifold.\n\n Returns\n -------\n tangent_vec : array-like, shape=[..., dim]\n Tangent vector at base point.\n '<|docstring|>Project a vector to a tangent space of the manifold. Parameters ---------- vector : array-like, shape=[..., dim] Vector. base_point : array-like, shape=[..., dim] Point on the manifold. Returns ------- tangent_vec : array-like, shape=[..., dim] Tangent vector at base point.<|endoftext|>
c181e0d12b46cb15d1665dc62681883d99c1d555f6a9f504b20ebb04a7c22b23
@abc.abstractmethod def random_point(self, n_samples=1, bound=1.0): 'Sample random points on the manifold.\n\n If the manifold is compact, a uniform distribution is used.\n\n Parameters\n ----------\n n_samples : int\n Number of samples.\n Optional, default: 1.\n bound : float\n Bound of the interval in which to sample for non compact manifolds.\n Optional, default: 1.\n\n Returns\n -------\n samples : array-like, shape=[..., {dim, [n, n]}]\n Points sampled on the hypersphere.\n '
Sample random points on the manifold. If the manifold is compact, a uniform distribution is used. Parameters ---------- n_samples : int Number of samples. Optional, default: 1. bound : float Bound of the interval in which to sample for non compact manifolds. Optional, default: 1. Returns ------- samples : array-like, shape=[..., {dim, [n, n]}] Points sampled on the hypersphere.
geomstats/geometry/manifold.py
random_point
qbarthelemy/geomstats
743
python
@abc.abstractmethod def random_point(self, n_samples=1, bound=1.0): 'Sample random points on the manifold.\n\n If the manifold is compact, a uniform distribution is used.\n\n Parameters\n ----------\n n_samples : int\n Number of samples.\n Optional, default: 1.\n bound : float\n Bound of the interval in which to sample for non compact manifolds.\n Optional, default: 1.\n\n Returns\n -------\n samples : array-like, shape=[..., {dim, [n, n]}]\n Points sampled on the hypersphere.\n '
@abc.abstractmethod def random_point(self, n_samples=1, bound=1.0): 'Sample random points on the manifold.\n\n If the manifold is compact, a uniform distribution is used.\n\n Parameters\n ----------\n n_samples : int\n Number of samples.\n Optional, default: 1.\n bound : float\n Bound of the interval in which to sample for non compact manifolds.\n Optional, default: 1.\n\n Returns\n -------\n samples : array-like, shape=[..., {dim, [n, n]}]\n Points sampled on the hypersphere.\n '<|docstring|>Sample random points on the manifold. If the manifold is compact, a uniform distribution is used. Parameters ---------- n_samples : int Number of samples. Optional, default: 1. bound : float Bound of the interval in which to sample for non compact manifolds. Optional, default: 1. Returns ------- samples : array-like, shape=[..., {dim, [n, n]}] Points sampled on the hypersphere.<|endoftext|>
85ad6e8515e79921527f7971f5913b4c410a77ac6d8cdcfe5ef3444ca1b506d2
def regularize(self, point): 'Regularize a point to the canonical representation for the manifold.\n\n Parameters\n ----------\n point : array-like, shape=[..., dim]\n Point.\n\n Returns\n -------\n regularized_point : array-like, shape=[..., dim]\n Regularized point.\n ' regularized_point = point return regularized_point
Regularize a point to the canonical representation for the manifold. Parameters ---------- point : array-like, shape=[..., dim] Point. Returns ------- regularized_point : array-like, shape=[..., dim] Regularized point.
geomstats/geometry/manifold.py
regularize
qbarthelemy/geomstats
743
python
def regularize(self, point): 'Regularize a point to the canonical representation for the manifold.\n\n Parameters\n ----------\n point : array-like, shape=[..., dim]\n Point.\n\n Returns\n -------\n regularized_point : array-like, shape=[..., dim]\n Regularized point.\n ' regularized_point = point return regularized_point
def regularize(self, point): 'Regularize a point to the canonical representation for the manifold.\n\n Parameters\n ----------\n point : array-like, shape=[..., dim]\n Point.\n\n Returns\n -------\n regularized_point : array-like, shape=[..., dim]\n Regularized point.\n ' regularized_point = point return regularized_point<|docstring|>Regularize a point to the canonical representation for the manifold. Parameters ---------- point : array-like, shape=[..., dim] Point. Returns ------- regularized_point : array-like, shape=[..., dim] Regularized point.<|endoftext|>
bbbafbc8f266cb4f089778e3c1c07c41e973cae2923086c5d658dde241b575d8
@property def metric(self): 'Riemannian Metric associated to the Manifold.' return self._metric
Riemannian Metric associated to the Manifold.
geomstats/geometry/manifold.py
metric
qbarthelemy/geomstats
743
python
@property def metric(self): return self._metric
@property def metric(self): return self._metric<|docstring|>Riemannian Metric associated to the Manifold.<|endoftext|>
b086de90055d370c65a9d3853a52387f073a156051a4fcf17179a6cffe76e937
def run_ipython_shell_v10(locals, globals, first_time): 'IPython shell from IPython version 0.10' if first_time: banner = 'Hit Ctrl-D to return to PuDB.' else: banner = '' ns = locals.copy() from IPython.Shell import IPShell IPShell(argv=[], user_ns=ns, user_global_ns=globals).mainloop(banner=banner)
IPython shell from IPython version 0.10
pudb/shell.py
run_ipython_shell_v10
flupke/pudb
0
python
def run_ipython_shell_v10(locals, globals, first_time): if first_time: banner = 'Hit Ctrl-D to return to PuDB.' else: banner = ns = locals.copy() from IPython.Shell import IPShell IPShell(argv=[], user_ns=ns, user_global_ns=globals).mainloop(banner=banner)
def run_ipython_shell_v10(locals, globals, first_time): if first_time: banner = 'Hit Ctrl-D to return to PuDB.' else: banner = ns = locals.copy() from IPython.Shell import IPShell IPShell(argv=[], user_ns=ns, user_global_ns=globals).mainloop(banner=banner)<|docstring|>IPython shell from IPython version 0.10<|endoftext|>
00a71b5cb4f8d4f333dcb87ae9de0e7914a8975117fdbff5756b78a32de737a6
def run_ipython_shell_v11(locals, globals, first_time): 'IPython shell from IPython version 0.11' if first_time: banner = 'Hit Ctrl-D to return to PuDB.' else: banner = '' from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell from IPython.frontend.terminal.ipapp import load_default_config config = load_default_config() shell = TerminalInteractiveShell.instance(config=config, banner2=banner) shell.history_manager.new_session() old_locals = shell.user_ns old_globals = shell.user_global_ns _update_ns(shell, locals, globals) shell.mainloop(banner) _update_ns(shell, old_locals, old_globals)
IPython shell from IPython version 0.11
pudb/shell.py
run_ipython_shell_v11
flupke/pudb
0
python
def run_ipython_shell_v11(locals, globals, first_time): if first_time: banner = 'Hit Ctrl-D to return to PuDB.' else: banner = from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell from IPython.frontend.terminal.ipapp import load_default_config config = load_default_config() shell = TerminalInteractiveShell.instance(config=config, banner2=banner) shell.history_manager.new_session() old_locals = shell.user_ns old_globals = shell.user_global_ns _update_ns(shell, locals, globals) shell.mainloop(banner) _update_ns(shell, old_locals, old_globals)
def run_ipython_shell_v11(locals, globals, first_time): if first_time: banner = 'Hit Ctrl-D to return to PuDB.' else: banner = from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell from IPython.frontend.terminal.ipapp import load_default_config config = load_default_config() shell = TerminalInteractiveShell.instance(config=config, banner2=banner) shell.history_manager.new_session() old_locals = shell.user_ns old_globals = shell.user_global_ns _update_ns(shell, locals, globals) shell.mainloop(banner) _update_ns(shell, old_locals, old_globals)<|docstring|>IPython shell from IPython version 0.11<|endoftext|>
9898a5e40e09d52aa90632ac09e8ebc93c7f404505d3111951d42dcb8629cd8e
def _update_ns(shell, locals, globals): 'Update the IPython 0.11 namespace at every visit' shell.user_ns = locals.copy() try: shell.user_global_ns = globals except AttributeError: class DummyMod(object): "A dummy module used for IPython's interactive namespace." pass user_module = DummyMod() user_module.__dict__ = globals shell.user_module = user_module shell.init_user_ns() shell.init_completer()
Update the IPython 0.11 namespace at every visit
pudb/shell.py
_update_ns
flupke/pudb
0
python
def _update_ns(shell, locals, globals): shell.user_ns = locals.copy() try: shell.user_global_ns = globals except AttributeError: class DummyMod(object): "A dummy module used for IPython's interactive namespace." pass user_module = DummyMod() user_module.__dict__ = globals shell.user_module = user_module shell.init_user_ns() shell.init_completer()
def _update_ns(shell, locals, globals): shell.user_ns = locals.copy() try: shell.user_global_ns = globals except AttributeError: class DummyMod(object): "A dummy module used for IPython's interactive namespace." pass user_module = DummyMod() user_module.__dict__ = globals shell.user_module = user_module shell.init_user_ns() shell.init_completer()<|docstring|>Update the IPython 0.11 namespace at every visit<|endoftext|>
cc40b86a98a04e34b96e2c76b659947e7dde5bb69411e64d694e213da6b88d6a
@classmethod def main(cls, args): ' generated source for method main ' GamerLogger.setSpilloverLogfile('spilloverLog') GamerLogger.log('Proxy', 'Starting the ProxyGamePlayerClient program.') if (not len(args)): GamerLogger.logError('Proxy', 'Usage is: \n\tProxyGamePlayerClient gamer port') return port = 9147 gamer = None try: port = Integer.valueOf(args[1]) except Exception as e: GamerLogger.logError('Proxy', (args[1] + ' is not a valid port.')) return gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()) gamerNames = ArrayList() if (len(gamerNames) != len(gamers)): for c in gamers: gamerNames.add(c.__name__.replaceAll('^.*\\.', '')) idx = gamerNames.indexOf(args[0]) if (idx == (- 1)): GamerLogger.logError('Proxy', (args[0] + ' is not a subclass of gamer. Valid options are:')) for s in gamerNames: GamerLogger.logError('Proxy', ('\t' + s)) return try: gamer = gamers.get(idx).newInstance() except Exception as ex: GamerLogger.logError('Proxy', ('Cannot create instance of ' + args[0])) return try: theClient.start() except IOException as e: GamerLogger.logStackTrace('Proxy', e)
generated source for method main
ggpy/cruft/autocode/ProxyGamePlayerClient.py
main
hobson/ggpy
1
python
@classmethod def main(cls, args): ' ' GamerLogger.setSpilloverLogfile('spilloverLog') GamerLogger.log('Proxy', 'Starting the ProxyGamePlayerClient program.') if (not len(args)): GamerLogger.logError('Proxy', 'Usage is: \n\tProxyGamePlayerClient gamer port') return port = 9147 gamer = None try: port = Integer.valueOf(args[1]) except Exception as e: GamerLogger.logError('Proxy', (args[1] + ' is not a valid port.')) return gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()) gamerNames = ArrayList() if (len(gamerNames) != len(gamers)): for c in gamers: gamerNames.add(c.__name__.replaceAll('^.*\\.', )) idx = gamerNames.indexOf(args[0]) if (idx == (- 1)): GamerLogger.logError('Proxy', (args[0] + ' is not a subclass of gamer. Valid options are:')) for s in gamerNames: GamerLogger.logError('Proxy', ('\t' + s)) return try: gamer = gamers.get(idx).newInstance() except Exception as ex: GamerLogger.logError('Proxy', ('Cannot create instance of ' + args[0])) return try: theClient.start() except IOException as e: GamerLogger.logStackTrace('Proxy', e)
@classmethod def main(cls, args): ' ' GamerLogger.setSpilloverLogfile('spilloverLog') GamerLogger.log('Proxy', 'Starting the ProxyGamePlayerClient program.') if (not len(args)): GamerLogger.logError('Proxy', 'Usage is: \n\tProxyGamePlayerClient gamer port') return port = 9147 gamer = None try: port = Integer.valueOf(args[1]) except Exception as e: GamerLogger.logError('Proxy', (args[1] + ' is not a valid port.')) return gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()) gamerNames = ArrayList() if (len(gamerNames) != len(gamers)): for c in gamers: gamerNames.add(c.__name__.replaceAll('^.*\\.', )) idx = gamerNames.indexOf(args[0]) if (idx == (- 1)): GamerLogger.logError('Proxy', (args[0] + ' is not a subclass of gamer. Valid options are:')) for s in gamerNames: GamerLogger.logError('Proxy', ('\t' + s)) return try: gamer = gamers.get(idx).newInstance() except Exception as ex: GamerLogger.logError('Proxy', ('Cannot create instance of ' + args[0])) return try: theClient.start() except IOException as e: GamerLogger.logStackTrace('Proxy', e)<|docstring|>generated source for method main<|endoftext|>
5dd2856f519ba81afad65658fc638b5134baaeef46614e770cf0378264d4b28a
def __init__(self, port, gamer): ' generated source for method __init__ ' super(ProxyGamePlayerClient, self).__init__() self.observers = ArrayList() self.theConnection = Socket('127.0.0.1', port) self.theOutput = PrintStream(self.theConnection.getOutputStream()) self.theInput = BufferedReader(InputStreamReader(self.theConnection.getInputStream())) self.gamer = gamer gamer.addObserver(self)
generated source for method __init__
ggpy/cruft/autocode/ProxyGamePlayerClient.py
__init__
hobson/ggpy
1
python
def __init__(self, port, gamer): ' ' super(ProxyGamePlayerClient, self).__init__() self.observers = ArrayList() self.theConnection = Socket('127.0.0.1', port) self.theOutput = PrintStream(self.theConnection.getOutputStream()) self.theInput = BufferedReader(InputStreamReader(self.theConnection.getInputStream())) self.gamer = gamer gamer.addObserver(self)
def __init__(self, port, gamer): ' ' super(ProxyGamePlayerClient, self).__init__() self.observers = ArrayList() self.theConnection = Socket('127.0.0.1', port) self.theOutput = PrintStream(self.theConnection.getOutputStream()) self.theInput = BufferedReader(InputStreamReader(self.theConnection.getInputStream())) self.gamer = gamer gamer.addObserver(self)<|docstring|>generated source for method __init__<|endoftext|>
ceaa5a1bb0657f062739249c2ebfb2590a91d1d9048974538a056049622a0408
def addObserver(self, observer): ' generated source for method addObserver ' self.observers.add(observer)
generated source for method addObserver
ggpy/cruft/autocode/ProxyGamePlayerClient.py
addObserver
hobson/ggpy
1
python
def addObserver(self, observer): ' ' self.observers.add(observer)
def addObserver(self, observer): ' ' self.observers.add(observer)<|docstring|>generated source for method addObserver<|endoftext|>
d0ef463d863dafae161bd47c7371610dd17c8a60ee1ec4ac9b5f05a0c226e0c2
def notifyObservers(self, event): ' generated source for method notifyObservers ' for observer in observers: observer.observe(event)
generated source for method notifyObservers
ggpy/cruft/autocode/ProxyGamePlayerClient.py
notifyObservers
hobson/ggpy
1
python
def notifyObservers(self, event): ' ' for observer in observers: observer.observe(event)
def notifyObservers(self, event): ' ' for observer in observers: observer.observe(event)<|docstring|>generated source for method notifyObservers<|endoftext|>
70bd937f5751a7d20c13036c62fefa0ebd151ad2c2e1082bb0b97532dca880eb
def run(self): ' generated source for method run ' while (not isInterrupted()): try: GamerLogger.log('Proxy', ('[ProxyClient] Got message: ' + theMessage)) self.theCode = theMessage.messageCode self.notifyObservers(PlayerReceivedMessageEvent(in_)) if isinstance(request, (StartRequest,)): RequestFactory().create(theDefaultGamer, in_).process(1) GamerLogger.startFileLogging(theDefaultGamer.getMatch(), theDefaultGamer.getRoleName().__str__()) GamerLogger.log('Proxy', ('[ProxyClient] Got message: ' + theMessage)) outMessage.writeTo(self.theOutput) GamerLogger.log('Proxy', ('[ProxyClient] Sent message: ' + outMessage)) self.notifyObservers(PlayerSentMessageEvent(out)) if isinstance(request, (StopRequest,)): GamerLogger.log('Proxy', '[ProxyClient] Got stop request, shutting down.') System.exit(0) if isinstance(request, (AbortRequest,)): GamerLogger.log('Proxy', '[ProxyClient] Got abort request, shutting down.') System.exit(0) except Exception as e: GamerLogger.logStackTrace('Proxy', e) self.notifyObservers(PlayerDroppedPacketEvent()) GamerLogger.log('Proxy', '[ProxyClient] Got interrupted, shutting down.')
generated source for method run
ggpy/cruft/autocode/ProxyGamePlayerClient.py
run
hobson/ggpy
1
python
def run(self): ' ' while (not isInterrupted()): try: GamerLogger.log('Proxy', ('[ProxyClient] Got message: ' + theMessage)) self.theCode = theMessage.messageCode self.notifyObservers(PlayerReceivedMessageEvent(in_)) if isinstance(request, (StartRequest,)): RequestFactory().create(theDefaultGamer, in_).process(1) GamerLogger.startFileLogging(theDefaultGamer.getMatch(), theDefaultGamer.getRoleName().__str__()) GamerLogger.log('Proxy', ('[ProxyClient] Got message: ' + theMessage)) outMessage.writeTo(self.theOutput) GamerLogger.log('Proxy', ('[ProxyClient] Sent message: ' + outMessage)) self.notifyObservers(PlayerSentMessageEvent(out)) if isinstance(request, (StopRequest,)): GamerLogger.log('Proxy', '[ProxyClient] Got stop request, shutting down.') System.exit(0) if isinstance(request, (AbortRequest,)): GamerLogger.log('Proxy', '[ProxyClient] Got abort request, shutting down.') System.exit(0) except Exception as e: GamerLogger.logStackTrace('Proxy', e) self.notifyObservers(PlayerDroppedPacketEvent()) GamerLogger.log('Proxy', '[ProxyClient] Got interrupted, shutting down.')
def run(self): ' ' while (not isInterrupted()): try: GamerLogger.log('Proxy', ('[ProxyClient] Got message: ' + theMessage)) self.theCode = theMessage.messageCode self.notifyObservers(PlayerReceivedMessageEvent(in_)) if isinstance(request, (StartRequest,)): RequestFactory().create(theDefaultGamer, in_).process(1) GamerLogger.startFileLogging(theDefaultGamer.getMatch(), theDefaultGamer.getRoleName().__str__()) GamerLogger.log('Proxy', ('[ProxyClient] Got message: ' + theMessage)) outMessage.writeTo(self.theOutput) GamerLogger.log('Proxy', ('[ProxyClient] Sent message: ' + outMessage)) self.notifyObservers(PlayerSentMessageEvent(out)) if isinstance(request, (StopRequest,)): GamerLogger.log('Proxy', '[ProxyClient] Got stop request, shutting down.') System.exit(0) if isinstance(request, (AbortRequest,)): GamerLogger.log('Proxy', '[ProxyClient] Got abort request, shutting down.') System.exit(0) except Exception as e: GamerLogger.logStackTrace('Proxy', e) self.notifyObservers(PlayerDroppedPacketEvent()) GamerLogger.log('Proxy', '[ProxyClient] Got interrupted, shutting down.')<|docstring|>generated source for method run<|endoftext|>
538a0d165c57c1a06706dc29390e91e6ef58912886d68883b9ab69c8f9025c71
def observe(self, event): ' generated source for method observe ' if isinstance(event, (WorkingResponseSelectedEvent,)): theMessage.writeTo(self.theOutput) GamerLogger.log('Proxy', ('[ProxyClient] Sent message: ' + theMessage))
generated source for method observe
ggpy/cruft/autocode/ProxyGamePlayerClient.py
observe
hobson/ggpy
1
python
def observe(self, event): ' ' if isinstance(event, (WorkingResponseSelectedEvent,)): theMessage.writeTo(self.theOutput) GamerLogger.log('Proxy', ('[ProxyClient] Sent message: ' + theMessage))
def observe(self, event): ' ' if isinstance(event, (WorkingResponseSelectedEvent,)): theMessage.writeTo(self.theOutput) GamerLogger.log('Proxy', ('[ProxyClient] Sent message: ' + theMessage))<|docstring|>generated source for method observe<|endoftext|>
a96a837057f2d48a8924ef32c05496eb347c398ad8ce40083678b51cee4defe9
def points(self): '\n return points of rebar in a list.\n list contain pairs of (x, y) coordinates\n ' p2 = Point(*self.insert).plusx(self.length) return [self.insert, tuple(p2)]
return points of rebar in a list. list contain pairs of (x, y) coordinates
pyconcrete/rebar.py
points
SurajDadral/pyconcrete
19
python
def points(self): '\n return points of rebar in a list.\n list contain pairs of (x, y) coordinates\n ' p2 = Point(*self.insert).plusx(self.length) return [self.insert, tuple(p2)]
def points(self): '\n return points of rebar in a list.\n list contain pairs of (x, y) coordinates\n ' p2 = Point(*self.insert).plusx(self.length) return [self.insert, tuple(p2)]<|docstring|>return points of rebar in a list. list contain pairs of (x, y) coordinates<|endoftext|>
6e96c25df56927439b73dbef035e5f18e39dbde49e90c53db027b486a660ca36
def base_points(self): '\n using base point for calculating points_along in\n inheritance class\n ' p2 = Point(*self.insert).plusx(self.length) return [self.insert, tuple(p2)]
using base point for calculating points_along in inheritance class
pyconcrete/rebar.py
base_points
SurajDadral/pyconcrete
19
python
def base_points(self): '\n using base point for calculating points_along in\n inheritance class\n ' p2 = Point(*self.insert).plusx(self.length) return [self.insert, tuple(p2)]
def base_points(self): '\n using base point for calculating points_along in\n inheritance class\n ' p2 = Point(*self.insert).plusx(self.length) return [self.insert, tuple(p2)]<|docstring|>using base point for calculating points_along in inheritance class<|endoftext|>
41649f758f747d4de1ea51ddb5b5ae373aa435f0ababd4e93b31fc9e0111c270
@property def text(self): "\n return text in format 'count~diameter'\n " return f'{self.count}~{self.diameter}'
return text in format 'count~diameter'
pyconcrete/rebar.py
text
SurajDadral/pyconcrete
19
python
@property def text(self): "\n \n " return f'{self.count}~{self.diameter}'
@property def text(self): "\n \n " return f'{self.count}~{self.diameter}'<|docstring|>return text in format 'count~diameter'<|endoftext|>
ebb7fceb80f9b46020b7be6e29e99b4af867fcf498dd7142a579acb40b6df735
def parse_args(args): '\n 解析命令参数\n ' parser = argparse.ArgumentParser(prog=version.__prog_name__, description=version.__description__) parser.add_argument('-v', '--version', action='version', version=('%(prog)s ' + version.__version__)) parser.add_argument('-d', '--debug', action='store_true', default=DEFAULT_DEBUG_MODE, help='print debug information') parser.add_argument('-p', '--port', type=int, default=DEFAULT_SERVICE_PORT, metavar='port', help='specify the port to listen') parser.add_argument('-s', '--save', default=DEFAULT_DATEBASE, metavar='database', dest='database', help='specify the database file') parser.add_argument('-c', '--cache', default=DEFAULT_CACHE_PATH, metavar='cache', dest='cache', help='specify the cache path') parser.add_argument('-l', '--log', default=DEFAULT_LOG_PATH, metavar='log', dest='log', help='specify the log files path') parser.add_argument('-q', '--quiet', action='store_true', default=DEFAULT_SILENT_MODE, help='switch on silent mode') return parser.parse_args(args)
解析命令参数
src/service/main.py
parse_args
tabris17/doufen
152
python
def parse_args(args): '\n \n ' parser = argparse.ArgumentParser(prog=version.__prog_name__, description=version.__description__) parser.add_argument('-v', '--version', action='version', version=('%(prog)s ' + version.__version__)) parser.add_argument('-d', '--debug', action='store_true', default=DEFAULT_DEBUG_MODE, help='print debug information') parser.add_argument('-p', '--port', type=int, default=DEFAULT_SERVICE_PORT, metavar='port', help='specify the port to listen') parser.add_argument('-s', '--save', default=DEFAULT_DATEBASE, metavar='database', dest='database', help='specify the database file') parser.add_argument('-c', '--cache', default=DEFAULT_CACHE_PATH, metavar='cache', dest='cache', help='specify the cache path') parser.add_argument('-l', '--log', default=DEFAULT_LOG_PATH, metavar='log', dest='log', help='specify the log files path') parser.add_argument('-q', '--quiet', action='store_true', default=DEFAULT_SILENT_MODE, help='switch on silent mode') return parser.parse_args(args)
def parse_args(args): '\n \n ' parser = argparse.ArgumentParser(prog=version.__prog_name__, description=version.__description__) parser.add_argument('-v', '--version', action='version', version=('%(prog)s ' + version.__version__)) parser.add_argument('-d', '--debug', action='store_true', default=DEFAULT_DEBUG_MODE, help='print debug information') parser.add_argument('-p', '--port', type=int, default=DEFAULT_SERVICE_PORT, metavar='port', help='specify the port to listen') parser.add_argument('-s', '--save', default=DEFAULT_DATEBASE, metavar='database', dest='database', help='specify the database file') parser.add_argument('-c', '--cache', default=DEFAULT_CACHE_PATH, metavar='cache', dest='cache', help='specify the cache path') parser.add_argument('-l', '--log', default=DEFAULT_LOG_PATH, metavar='log', dest='log', help='specify the log files path') parser.add_argument('-q', '--quiet', action='store_true', default=DEFAULT_SILENT_MODE, help='switch on silent mode') return parser.parse_args(args)<|docstring|>解析命令参数<|endoftext|>
18c25e218f89301c5fce46adb31335bdbb2ef3979b7dc35f8757718c84b77e4e
def main(args): '\n 程序主函数\n ' parsed_args = parse_args(args) settings.update({'cache': parsed_args.cache, 'log': parsed_args.log, 'database': parsed_args.database, 'port': parsed_args.port, 'debug': parsed_args.debug, 'quiet': parsed_args.quiet}) init_env() init_logger() db.init(parsed_args.database) server = Server(parsed_args.port, DEFAULT_SERVICE_HOST, parsed_args.cache) server.run()
程序主函数
src/service/main.py
main
tabris17/doufen
152
python
def main(args): '\n \n ' parsed_args = parse_args(args) settings.update({'cache': parsed_args.cache, 'log': parsed_args.log, 'database': parsed_args.database, 'port': parsed_args.port, 'debug': parsed_args.debug, 'quiet': parsed_args.quiet}) init_env() init_logger() db.init(parsed_args.database) server = Server(parsed_args.port, DEFAULT_SERVICE_HOST, parsed_args.cache) server.run()
def main(args): '\n \n ' parsed_args = parse_args(args) settings.update({'cache': parsed_args.cache, 'log': parsed_args.log, 'database': parsed_args.database, 'port': parsed_args.port, 'debug': parsed_args.debug, 'quiet': parsed_args.quiet}) init_env() init_logger() db.init(parsed_args.database) server = Server(parsed_args.port, DEFAULT_SERVICE_HOST, parsed_args.cache) server.run()<|docstring|>程序主函数<|endoftext|>
df3ead234abe2cd698f138568a624bff96265888d7cd9f870a32b0f4d57b38b1
def copy_obj(): ' 多个文件复制到一个文件 ' bufsize = (16 * 1024) with open('test.txt', 'wb') as out_file: cwd = Path.cwd() for child in cwd.iterdir(): print(child) if (child.is_file() and (child.name != 'test.txt')): with child.open('rb') as in_file: shutil.copyfileobj(in_file, out_file)
多个文件复制到一个文件
src/06_tool/demo_shutil.py
copy_obj
edgardeng/python-advance-interview
1
python
def copy_obj(): ' ' bufsize = (16 * 1024) with open('test.txt', 'wb') as out_file: cwd = Path.cwd() for child in cwd.iterdir(): print(child) if (child.is_file() and (child.name != 'test.txt')): with child.open('rb') as in_file: shutil.copyfileobj(in_file, out_file)
def copy_obj(): ' ' bufsize = (16 * 1024) with open('test.txt', 'wb') as out_file: cwd = Path.cwd() for child in cwd.iterdir(): print(child) if (child.is_file() and (child.name != 'test.txt')): with child.open('rb') as in_file: shutil.copyfileobj(in_file, out_file)<|docstring|>多个文件复制到一个文件<|endoftext|>
ab088c029991525d7fce3afec55b4de9740e8779aad6ea8658342321c2139f7a
def extract_version() -> str: '\n Extract version from .py file using regex\n\n :return: odahuflow version\n ' with open(VERSION_FILE, 'rt') as version_file: file_content = version_file.read() VSRE = '^__version__ = [\'\\"]([^\'\\"]*)[\'\\"]' mo = re.search(VSRE, file_content, re.M) if mo: return mo.group(1) else: raise RuntimeError(('Unable to find version string in %s.' % (file_content,)))
Extract version from .py file using regex :return: odahuflow version
setup.py
extract_version
odahu/odahuJupyterLab
4
python
def extract_version() -> str: '\n Extract version from .py file using regex\n\n :return: odahuflow version\n ' with open(VERSION_FILE, 'rt') as version_file: file_content = version_file.read() VSRE = '^__version__ = [\'\\"]([^\'\\"]*)[\'\\"]' mo = re.search(VSRE, file_content, re.M) if mo: return mo.group(1) else: raise RuntimeError(('Unable to find version string in %s.' % (file_content,)))
def extract_version() -> str: '\n Extract version from .py file using regex\n\n :return: odahuflow version\n ' with open(VERSION_FILE, 'rt') as version_file: file_content = version_file.read() VSRE = '^__version__ = [\'\\"]([^\'\\"]*)[\'\\"]' mo = re.search(VSRE, file_content, re.M) if mo: return mo.group(1) else: raise RuntimeError(('Unable to find version string in %s.' % (file_content,)))<|docstring|>Extract version from .py file using regex :return: odahuflow version<|endoftext|>
182df06e09fed67e943b2e3bb279f75ed3155b9cf3c81dd8f59cd289c7120403
async def main() -> None: 'doc' bot = MyBot().use(Task()) os.environ['WECHATY_PUPPET'] = 'wechaty-puppet-padlocal' os.environ['WECHATY_PUPPET_SERVICE_ENDPOINT'] = '192.168.1.124:8788' (await bot.start())
doc
app/robot.py
main
anonier/python-wechaty
0
python
async def main() -> None: bot = MyBot().use(Task()) os.environ['WECHATY_PUPPET'] = 'wechaty-puppet-padlocal' os.environ['WECHATY_PUPPET_SERVICE_ENDPOINT'] = '192.168.1.124:8788' (await bot.start())
async def main() -> None: bot = MyBot().use(Task()) os.environ['WECHATY_PUPPET'] = 'wechaty-puppet-padlocal' os.environ['WECHATY_PUPPET_SERVICE_ENDPOINT'] = '192.168.1.124:8788' (await bot.start())<|docstring|>doc<|endoftext|>
d368ec5e2fb3f99bb515a6fd04f3c4ad6b11223c0b2f817d541e1144900005ed
def __init__(self) -> None: 'initialization function\n ' self.login_user: Optional[Contact] = None super().__init__()
initialization function
app/robot.py
__init__
anonier/python-wechaty
0
python
def __init__(self) -> None: '\n ' self.login_user: Optional[Contact] = None super().__init__()
def __init__(self) -> None: '\n ' self.login_user: Optional[Contact] = None super().__init__()<|docstring|>initialization function<|endoftext|>
1ba60cde6b65646a31cdc9e9e67e94e93cd1ec970ae28b04d1c3e17c8accf915
async def on_ready(self, payload: EventReadyPayload) -> None: 'listen for on-ready event' logger.info('ready event %s...', payload)
listen for on-ready event
app/robot.py
on_ready
anonier/python-wechaty
0
python
async def on_ready(self, payload: EventReadyPayload) -> None: logger.info('ready event %s...', payload)
async def on_ready(self, payload: EventReadyPayload) -> None: logger.info('ready event %s...', payload)<|docstring|>listen for on-ready event<|endoftext|>
f93c7e888a35458d59919cb7ae5cc53816d92a2f806bc72f767a7b765d4319d9
async def on_message(self, msg: Message) -> None: '\n listen for message event\n ' from_contact: Contact = msg.talker() contact_id = from_contact.contact_id text: str = msg.text() room: Optional[Room] = msg.room() room_id = room.room_id msg_type: MessageType = msg.type() if ('25398111924@chatroom' == room_id): if (('@AI出单' in text) and ('查单' not in text) and ('报价' not in text) and (text.count('出单') == 1) and ('录单' not in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) elif (('@AI出单' in text) and ('查单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/policy.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] if ((len(x) != 4) or (len(man_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) car_licence = [a for a in x if (('出单' not in a) and ('查单' not in a) and ('@' not in a) and ('业务员' not in a))] if ((len(car_licence) == 0) or not_car_number(license_plate, car_licence[0])): (await conversation.say((('@' + msg.talker().name) + ' 未识别到车辆信息,请核对信息!'))) return car_licence = car_licence[0] (await conversation.say((('@' + msg.talker().name) + ' 收到查单指令,识别到车辆信息,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '1', 'cmdName': text, 'salesman': salesman, 'licenseId': car_licence, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: (await conversation.say((((('@' + msg.talker().name) + ' 请查看') + car_licence) + '的电子保单文件!'))) for (key, value) in response_dict['data'].items(): file_box = FileBox.from_url(value, name=key) (await conversation.say(file_box)) return num = (num + 1) elif (('@AI出单' in text) and ('报价' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/declaration.do') x = text.split() insurance_cmd = [a for a in x if ('险种' in a)] man_cmd = [a for a in x if ('业务员' in a)] if (((len(x) != 5) and (len(x) != 7)) or (len(man_cmd) == 0) or (len(insurance_cmd) == 0) or (len(insurance_cmd) > 1) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) insurance = (insurance_cmd[0].split(':')[1] if (':' in insurance_cmd[0]) else insurance_cmd[0].split(':')[1]) if ('基本' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('100' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('1' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('1' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return elif ('进阶' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('150' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('5' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('5' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return szInsurance = szInsurance[0] driver = driver[0] passenger = passenger[0] (await conversation.say((('@' + msg.talker().name) + ' 收到报价指令,努力处理中,请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '2', 'cmdName': text, 'appKey': 'X08ASKYS', 'jqInsurance': jqInsurance, 'csInsurance': csInsurance, 'szInsurance': szInsurance, 'salesman': salesman, 'driver': driver, 'passenger': passenger, 'accident': (None if (accident is None) else '*'.join(accident)), 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: try: data = response_dict['data'] (await conversation.say((((((((((('@' + msg.talker().name) + ' 本车客户风险等级:') + data['customerRiskRating']) + '; 车系风险等级:') + data['familyGrade']) + '; 无赔系数:') + data['unattendGrade']) + '; 自主定价系数:') + data['rateProduct']) + '。'))) (await conversation.say((((((((((((((((((((((((((((((('@' + msg.talker().name) + ' ') + data['ownerName']) + ',您好!您的爱车') + data['plateNumber']) + '预计估价共计') + data['totalPremium']) + '元,其中交强险') + data['compulsoryPremium']) + '元, 商业险') + data['businessPremium']) + '元。商业险明细:车损保额') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['premium']) + '元 ;三者保额') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['premium']) + '元 ;司机保额') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['premium']) + '元;乘客保额') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['premium']) + '元 。代收车船税') + data['taxPremium']) + '元。此报价仅供参考,最终价格以出单为准。'))) file_box = FileBox.from_url(data['url'], name='policy.jpg') (await conversation.say(file_box)) return except: (await conversation.say((('@' + msg.talker().name) + ' 操作报价失败,请手动操作!'))) return num = (num + 1) elif (('@AI出单' in text) and (text.count('出单') == 2)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/issuing.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] if ((len(x) < 4) or (len(x) > 5) or (len(man_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) car_licence = [a for a in x if (('出单' not in a) and ('@' not in a) and ('业务员' not in a))] if ((len(car_licence) == 0) or not_car_number(license_plate, car_licence[0])): (await conversation.say((('@' + msg.talker().name) + ' 未识别到车辆信息,请核对信息!'))) return car_licence = car_licence[0] (await conversation.say((('@' + msg.talker().name) + ' 收到出单指令,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '3', 'cmdName': text, 'salesman': salesman, 'licenseId': car_licence, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: (await conversation.say((('@' + msg.talker().name) + ' 已完成出单!'))) qr = FileBox.from_base64(open('qr.txt', 'rb').read(), 'qr.jpg') (await conversation.say(qr)) file_box = FileBox.from_base64(str.encode(str(response_dict['data']).split(',')[1]), name='qr.jpg') (await conversation.say(file_box)) return num = (num + 1) elif (('@AI出单' in text) and ('录单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/policy.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] phone_cmd = [a for a in x if ('手机' in a)] insurance_cmd = [a for a in x if ('险种' in a)] if ((len(x) != 8) or (len(man_cmd) == 0) or (len(phone_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0])) or ((':' not in phone_cmd[0]) and (':' not in phone_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) phone = (phone_cmd[0].split(':')[1] if (':' in phone_cmd[0]) else phone_cmd[0].split(':')[1]) insurance = (insurance_cmd[0].split(':')[1] if (':' in insurance_cmd[0]) else insurance_cmd[0].split(':')[1]) if ('基本' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('100' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('1' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('1' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return elif ('进阶' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('150' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('5' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('5' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return szInsurance = szInsurance[0] driver = driver[0] passenger = passenger[0] (await conversation.say((('@' + msg.talker().name) + ' 收到录单指令,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '4', 'cmdName': text, 'salesman': salesman, 'jqInsurance': jqInsurance, 'csInsurance': csInsurance, 'szInsurance': szInsurance, 'driver': driver, 'passenger': passenger, 'accident': (None if (accident is None) else '*'.join(accident)), 'phone': phone, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return (await conversation.say((('@' + msg.talker().name) + ' 已完成录单!'))) num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: try: data = response_dict['data'] (await conversation.say((((((((((('@' + msg.talker().name) + ' 本车客户风险等级:') + data['customerRiskRating']) + '; 车系风险等级:') + data['familyGrade']) + '; 无赔系数:') + data['unattendGrade']) + '; 自主定价系数:') + data['rateProduct']) + '。'))) (await conversation.say((((((((((((((((((((((((((((((('@' + msg.talker().name) + ' ') + data['ownerName']) + ',您好!您的爱车') + data['plateNumber']) + '预计估价共计') + data['totalPremium']) + '元,其中交强险') + data['compulsoryPremium']) + '元, 商业险') + data['businessPremium']) + '元。商业险明细:车损保额') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['premium']) + '元 ;三者保额') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['premium']) + '元 ;司机保额') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['premium']) + '元;乘客保额') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['premium']) + '元 。代收车船税') + data['taxPremium']) + '元。此报价仅供参考,最终价格以出单为准。'))) file_box = FileBox.from_url(data['url'], name='policy.jpg') (await conversation.say(file_box)) return except: (await conversation.say((('@' + msg.talker().name) + ' 操作报价失败,请手动操作!'))) return return num = (num + 1) elif (msg_type == MessageType.MESSAGE_TYPE_IMAGE): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info('receving image file') image: WeImage = msg.to_image() hd_file_box: FileBox = (await image.hd()) url = (ip + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': ((str(int(time.time())) + '.jpg'), BytesIO(hd_file_box.stream), 'image/jpeg'), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) else: pass if (msg.type() == MessageType.MESSAGE_TYPE_UNSPECIFIED): talker = msg.talker() assert isinstance(talker, Contact) elif ('21121012651@chatroom' == room_id): if (('@AI出单' in text) and ('查单' in text)): pass elif (('@AI出单' in text) and ('批量出单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) (await conversation.say((('@' + msg.talker().name) + ' 收到指令,努力处理中请稍后!'))) url = (ip_js + 'api/RobotApi/wycPolicy.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': msg.talker().name, 'cmdName': text, 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip_js + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ''): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return elif response_dict['success']: try: file_box = FileBox.from_url(response_dict['data'], name='policy.xlsx') (await conversation.say(file_box)) (await conversation.say((('@' + msg.talker().name) + ' 完成批量出单,请查收结果!'))) return except: (await conversation.say((('@' + msg.talker().name) + ' 批量出单失败,请手动操作!'))) return num = (num + 1) elif (msg_type == MessageType.MESSAGE_TYPE_IMAGE): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info('receving image file') image: WeImage = msg.to_image() hd_file_box: FileBox = (await image.hd()) url = (ip_js + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': ((str(int(time.time())) + '.jpg'), BytesIO(hd_file_box.stream), 'image/jpeg'), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) elif (msg_type in [MessageType.MESSAGE_TYPE_AUDIO, MessageType.MESSAGE_TYPE_ATTACHMENT, MessageType.MESSAGE_TYPE_VIDEO]): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info(('receving file:' + 'test')) file_box = (await msg.to_file_box()) url = (ip_js + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'operator': '6', 'nickname': msg.talker().name, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': (((str(int(time.time())) + '.xlsx') if file_box.name.endswith('xlsx') else '.xls'), BytesIO(file_box.stream), ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' if file_box.name.endswith('xlsx') else 'application/vnd.ms-excel')), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) else: pass if (msg.type() == MessageType.MESSAGE_TYPE_UNSPECIFIED): talker = msg.talker() assert isinstance(talker, Contact) else: pass
listen for message event
app/robot.py
on_message
anonier/python-wechaty
0
python
async def on_message(self, msg: Message) -> None: '\n \n ' from_contact: Contact = msg.talker() contact_id = from_contact.contact_id text: str = msg.text() room: Optional[Room] = msg.room() room_id = room.room_id msg_type: MessageType = msg.type() if ('25398111924@chatroom' == room_id): if (('@AI出单' in text) and ('查单' not in text) and ('报价' not in text) and (text.count('出单') == 1) and ('录单' not in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) elif (('@AI出单' in text) and ('查单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/policy.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] if ((len(x) != 4) or (len(man_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) car_licence = [a for a in x if (('出单' not in a) and ('查单' not in a) and ('@' not in a) and ('业务员' not in a))] if ((len(car_licence) == 0) or not_car_number(license_plate, car_licence[0])): (await conversation.say((('@' + msg.talker().name) + ' 未识别到车辆信息,请核对信息!'))) return car_licence = car_licence[0] (await conversation.say((('@' + msg.talker().name) + ' 收到查单指令,识别到车辆信息,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '1', 'cmdName': text, 'salesman': salesman, 'licenseId': car_licence, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: (await conversation.say((((('@' + msg.talker().name) + ' 请查看') + car_licence) + '的电子保单文件!'))) for (key, value) in response_dict['data'].items(): file_box = FileBox.from_url(value, name=key) (await conversation.say(file_box)) return num = (num + 1) elif (('@AI出单' in text) and ('报价' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/declaration.do') x = text.split() insurance_cmd = [a for a in x if ('险种' in a)] man_cmd = [a for a in x if ('业务员' in a)] if (((len(x) != 5) and (len(x) != 7)) or (len(man_cmd) == 0) or (len(insurance_cmd) == 0) or (len(insurance_cmd) > 1) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) insurance = (insurance_cmd[0].split(':')[1] if (':' in insurance_cmd[0]) else insurance_cmd[0].split(':')[1]) if ('基本' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('100' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('1' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('1' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return elif ('进阶' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('150' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('5' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('5' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return szInsurance = szInsurance[0] driver = driver[0] passenger = passenger[0] (await conversation.say((('@' + msg.talker().name) + ' 收到报价指令,努力处理中,请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '2', 'cmdName': text, 'appKey': 'X08ASKYS', 'jqInsurance': jqInsurance, 'csInsurance': csInsurance, 'szInsurance': szInsurance, 'salesman': salesman, 'driver': driver, 'passenger': passenger, 'accident': (None if (accident is None) else '*'.join(accident)), 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: try: data = response_dict['data'] (await conversation.say((((((((((('@' + msg.talker().name) + ' 本车客户风险等级:') + data['customerRiskRating']) + '; 车系风险等级:') + data['familyGrade']) + '; 无赔系数:') + data['unattendGrade']) + '; 自主定价系数:') + data['rateProduct']) + '。'))) (await conversation.say((((((((((((((((((((((((((((((('@' + msg.talker().name) + ' ') + data['ownerName']) + ',您好!您的爱车') + data['plateNumber']) + '预计估价共计') + data['totalPremium']) + '元,其中交强险') + data['compulsoryPremium']) + '元, 商业险') + data['businessPremium']) + '元。商业险明细:车损保额') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['premium']) + '元 ;三者保额') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['premium']) + '元 ;司机保额') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['premium']) + '元;乘客保额') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['premium']) + '元 。代收车船税') + data['taxPremium']) + '元。此报价仅供参考,最终价格以出单为准。'))) file_box = FileBox.from_url(data['url'], name='policy.jpg') (await conversation.say(file_box)) return except: (await conversation.say((('@' + msg.talker().name) + ' 操作报价失败,请手动操作!'))) return num = (num + 1) elif (('@AI出单' in text) and (text.count('出单') == 2)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/issuing.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] if ((len(x) < 4) or (len(x) > 5) or (len(man_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) car_licence = [a for a in x if (('出单' not in a) and ('@' not in a) and ('业务员' not in a))] if ((len(car_licence) == 0) or not_car_number(license_plate, car_licence[0])): (await conversation.say((('@' + msg.talker().name) + ' 未识别到车辆信息,请核对信息!'))) return car_licence = car_licence[0] (await conversation.say((('@' + msg.talker().name) + ' 收到出单指令,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '3', 'cmdName': text, 'salesman': salesman, 'licenseId': car_licence, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: (await conversation.say((('@' + msg.talker().name) + ' 已完成出单!'))) qr = FileBox.from_base64(open('qr.txt', 'rb').read(), 'qr.jpg') (await conversation.say(qr)) file_box = FileBox.from_base64(str.encode(str(response_dict['data']).split(',')[1]), name='qr.jpg') (await conversation.say(file_box)) return num = (num + 1) elif (('@AI出单' in text) and ('录单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/policy.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] phone_cmd = [a for a in x if ('手机' in a)] insurance_cmd = [a for a in x if ('险种' in a)] if ((len(x) != 8) or (len(man_cmd) == 0) or (len(phone_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0])) or ((':' not in phone_cmd[0]) and (':' not in phone_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) phone = (phone_cmd[0].split(':')[1] if (':' in phone_cmd[0]) else phone_cmd[0].split(':')[1]) insurance = (insurance_cmd[0].split(':')[1] if (':' in insurance_cmd[0]) else insurance_cmd[0].split(':')[1]) if ('基本' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('100' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('1' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('1' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return elif ('进阶' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('150' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('5' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('5' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return szInsurance = szInsurance[0] driver = driver[0] passenger = passenger[0] (await conversation.say((('@' + msg.talker().name) + ' 收到录单指令,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '4', 'cmdName': text, 'salesman': salesman, 'jqInsurance': jqInsurance, 'csInsurance': csInsurance, 'szInsurance': szInsurance, 'driver': driver, 'passenger': passenger, 'accident': (None if (accident is None) else '*'.join(accident)), 'phone': phone, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return (await conversation.say((('@' + msg.talker().name) + ' 已完成录单!'))) num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: try: data = response_dict['data'] (await conversation.say((((((((((('@' + msg.talker().name) + ' 本车客户风险等级:') + data['customerRiskRating']) + '; 车系风险等级:') + data['familyGrade']) + '; 无赔系数:') + data['unattendGrade']) + '; 自主定价系数:') + data['rateProduct']) + '。'))) (await conversation.say((((((((((((((((((((((((((((((('@' + msg.talker().name) + ' ') + data['ownerName']) + ',您好!您的爱车') + data['plateNumber']) + '预计估价共计') + data['totalPremium']) + '元,其中交强险') + data['compulsoryPremium']) + '元, 商业险') + data['businessPremium']) + '元。商业险明细:车损保额') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['premium']) + '元 ;三者保额') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['premium']) + '元 ;司机保额') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['premium']) + '元;乘客保额') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['premium']) + '元 。代收车船税') + data['taxPremium']) + '元。此报价仅供参考,最终价格以出单为准。'))) file_box = FileBox.from_url(data['url'], name='policy.jpg') (await conversation.say(file_box)) return except: (await conversation.say((('@' + msg.talker().name) + ' 操作报价失败,请手动操作!'))) return return num = (num + 1) elif (msg_type == MessageType.MESSAGE_TYPE_IMAGE): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info('receving image file') image: WeImage = msg.to_image() hd_file_box: FileBox = (await image.hd()) url = (ip + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': ((str(int(time.time())) + '.jpg'), BytesIO(hd_file_box.stream), 'image/jpeg'), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) else: pass if (msg.type() == MessageType.MESSAGE_TYPE_UNSPECIFIED): talker = msg.talker() assert isinstance(talker, Contact) elif ('21121012651@chatroom' == room_id): if (('@AI出单' in text) and ('查单' in text)): pass elif (('@AI出单' in text) and ('批量出单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) (await conversation.say((('@' + msg.talker().name) + ' 收到指令,努力处理中请稍后!'))) url = (ip_js + 'api/RobotApi/wycPolicy.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': msg.talker().name, 'cmdName': text, 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip_js + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return elif response_dict['success']: try: file_box = FileBox.from_url(response_dict['data'], name='policy.xlsx') (await conversation.say(file_box)) (await conversation.say((('@' + msg.talker().name) + ' 完成批量出单,请查收结果!'))) return except: (await conversation.say((('@' + msg.talker().name) + ' 批量出单失败,请手动操作!'))) return num = (num + 1) elif (msg_type == MessageType.MESSAGE_TYPE_IMAGE): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info('receving image file') image: WeImage = msg.to_image() hd_file_box: FileBox = (await image.hd()) url = (ip_js + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': ((str(int(time.time())) + '.jpg'), BytesIO(hd_file_box.stream), 'image/jpeg'), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) elif (msg_type in [MessageType.MESSAGE_TYPE_AUDIO, MessageType.MESSAGE_TYPE_ATTACHMENT, MessageType.MESSAGE_TYPE_VIDEO]): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info(('receving file:' + 'test')) file_box = (await msg.to_file_box()) url = (ip_js + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'operator': '6', 'nickname': msg.talker().name, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': (((str(int(time.time())) + '.xlsx') if file_box.name.endswith('xlsx') else '.xls'), BytesIO(file_box.stream), ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' if file_box.name.endswith('xlsx') else 'application/vnd.ms-excel')), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) else: pass if (msg.type() == MessageType.MESSAGE_TYPE_UNSPECIFIED): talker = msg.talker() assert isinstance(talker, Contact) else: pass
async def on_message(self, msg: Message) -> None: '\n \n ' from_contact: Contact = msg.talker() contact_id = from_contact.contact_id text: str = msg.text() room: Optional[Room] = msg.room() room_id = room.room_id msg_type: MessageType = msg.type() if ('25398111924@chatroom' == room_id): if (('@AI出单' in text) and ('查单' not in text) and ('报价' not in text) and (text.count('出单') == 1) and ('录单' not in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) elif (('@AI出单' in text) and ('查单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/policy.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] if ((len(x) != 4) or (len(man_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) car_licence = [a for a in x if (('出单' not in a) and ('查单' not in a) and ('@' not in a) and ('业务员' not in a))] if ((len(car_licence) == 0) or not_car_number(license_plate, car_licence[0])): (await conversation.say((('@' + msg.talker().name) + ' 未识别到车辆信息,请核对信息!'))) return car_licence = car_licence[0] (await conversation.say((('@' + msg.talker().name) + ' 收到查单指令,识别到车辆信息,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '1', 'cmdName': text, 'salesman': salesman, 'licenseId': car_licence, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: (await conversation.say((((('@' + msg.talker().name) + ' 请查看') + car_licence) + '的电子保单文件!'))) for (key, value) in response_dict['data'].items(): file_box = FileBox.from_url(value, name=key) (await conversation.say(file_box)) return num = (num + 1) elif (('@AI出单' in text) and ('报价' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/declaration.do') x = text.split() insurance_cmd = [a for a in x if ('险种' in a)] man_cmd = [a for a in x if ('业务员' in a)] if (((len(x) != 5) and (len(x) != 7)) or (len(man_cmd) == 0) or (len(insurance_cmd) == 0) or (len(insurance_cmd) > 1) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) insurance = (insurance_cmd[0].split(':')[1] if (':' in insurance_cmd[0]) else insurance_cmd[0].split(':')[1]) if ('基本' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('100' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('1' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('1' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return elif ('进阶' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('150' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('5' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('5' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return szInsurance = szInsurance[0] driver = driver[0] passenger = passenger[0] (await conversation.say((('@' + msg.talker().name) + ' 收到报价指令,努力处理中,请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '2', 'cmdName': text, 'appKey': 'X08ASKYS', 'jqInsurance': jqInsurance, 'csInsurance': csInsurance, 'szInsurance': szInsurance, 'salesman': salesman, 'driver': driver, 'passenger': passenger, 'accident': (None if (accident is None) else '*'.join(accident)), 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: try: data = response_dict['data'] (await conversation.say((((((((((('@' + msg.talker().name) + ' 本车客户风险等级:') + data['customerRiskRating']) + '; 车系风险等级:') + data['familyGrade']) + '; 无赔系数:') + data['unattendGrade']) + '; 自主定价系数:') + data['rateProduct']) + '。'))) (await conversation.say((((((((((((((((((((((((((((((('@' + msg.talker().name) + ' ') + data['ownerName']) + ',您好!您的爱车') + data['plateNumber']) + '预计估价共计') + data['totalPremium']) + '元,其中交强险') + data['compulsoryPremium']) + '元, 商业险') + data['businessPremium']) + '元。商业险明细:车损保额') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['premium']) + '元 ;三者保额') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['premium']) + '元 ;司机保额') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['premium']) + '元;乘客保额') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['premium']) + '元 。代收车船税') + data['taxPremium']) + '元。此报价仅供参考,最终价格以出单为准。'))) file_box = FileBox.from_url(data['url'], name='policy.jpg') (await conversation.say(file_box)) return except: (await conversation.say((('@' + msg.talker().name) + ' 操作报价失败,请手动操作!'))) return num = (num + 1) elif (('@AI出单' in text) and (text.count('出单') == 2)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/issuing.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] if ((len(x) < 4) or (len(x) > 5) or (len(man_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) car_licence = [a for a in x if (('出单' not in a) and ('@' not in a) and ('业务员' not in a))] if ((len(car_licence) == 0) or not_car_number(license_plate, car_licence[0])): (await conversation.say((('@' + msg.talker().name) + ' 未识别到车辆信息,请核对信息!'))) return car_licence = car_licence[0] (await conversation.say((('@' + msg.talker().name) + ' 收到出单指令,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '3', 'cmdName': text, 'salesman': salesman, 'licenseId': car_licence, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: (await conversation.say((('@' + msg.talker().name) + ' 已完成出单!'))) qr = FileBox.from_base64(open('qr.txt', 'rb').read(), 'qr.jpg') (await conversation.say(qr)) file_box = FileBox.from_base64(str.encode(str(response_dict['data']).split(',')[1]), name='qr.jpg') (await conversation.say(file_box)) return num = (num + 1) elif (('@AI出单' in text) and ('录单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) url = (ip + 'api/RobotApi/policy.do') x = text.split() man_cmd = [a for a in x if ('业务员' in a)] phone_cmd = [a for a in x if ('手机' in a)] insurance_cmd = [a for a in x if ('险种' in a)] if ((len(x) != 8) or (len(man_cmd) == 0) or (len(phone_cmd) == 0) or ((':' not in man_cmd[0]) and (':' not in man_cmd[0])) or ((':' not in phone_cmd[0]) and (':' not in phone_cmd[0]))): (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return salesman = (man_cmd[0].split(':')[1] if (':' in man_cmd[0]) else man_cmd[0].split(':')[1]) phone = (phone_cmd[0].split(':')[1] if (':' in phone_cmd[0]) else phone_cmd[0].split(':')[1]) insurance = (insurance_cmd[0].split(':')[1] if (':' in insurance_cmd[0]) else insurance_cmd[0].split(':')[1]) if ('基本' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('100' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('1' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('1' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return elif ('进阶' in insurance): if (len(x) == 5): if (len([a for a in x if ('-商业' in a)]) != 0): jqInsurance = 'true' csInsurance = 'false' szInsurance = None driver = None passenger = None accident = None else: jqInsurance = ('false' if [a for a in x if ('-交强' in a)] else 'true') if (len([a for a in x if ('-车损' in a)]) != 0): csInsurance = 'false' elif (len([a for a in x if (('车损' in a) and ('-' not in a))]) != 0): csInsurance = get_number((a for a in x if ('车损' in a))) else: csInsurance = 'true' szInsurance = ('150' if (len([a for a in x if ('三者' in a)]) == 0) else get_number(str([a for a in x if ('三者' in a)]))) driver = ('5' if (len([a for a in x if ('司机' in a)]) == 0) else get_number(str([a for a in x if ('司机' in a)]))) passenger = ('5' if (len([a for a in x if ('乘客' in a)]) == 0) else get_number(str([a for a in x if ('乘客' in a)]))) accident = (None if (len([a for a in x if ('意外' in a)]) == 0) else get_number(str([a for a in x if ('意外' in a)]))) elif (len(x) == 7): jqInsurance = 'true' csInsurance = 'true' szInsurance = get_number(str([a for a in x if ('三者' in a)])) driver = get_number(str([a for a in x if ('司机' in a)])) passenger = get_number(str([a for a in x if ('乘客' in a)])) accident = None else: (await conversation.say((('@' + msg.talker().name) + ' 未识别到指令,请核实后重新发送!'))) return szInsurance = szInsurance[0] driver = driver[0] passenger = passenger[0] (await conversation.say((('@' + msg.talker().name) + ' 收到录单指令,数据处理中请稍后!'))) multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': '4', 'cmdName': text, 'salesman': salesman, 'jqInsurance': jqInsurance, 'csInsurance': csInsurance, 'szInsurance': szInsurance, 'driver': driver, 'passenger': passenger, 'accident': (None if (accident is None) else '*'.join(accident)), 'phone': phone, 'appKey': 'X08ASKYS', 'nickname': msg.talker().name}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return (await conversation.say((('@' + msg.talker().name) + ' 已完成录单!'))) num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 未查询到客户数据!'))) return elif response_dict['success']: try: data = response_dict['data'] (await conversation.say((((((((((('@' + msg.talker().name) + ' 本车客户风险等级:') + data['customerRiskRating']) + '; 车系风险等级:') + data['familyGrade']) + '; 无赔系数:') + data['unattendGrade']) + '; 自主定价系数:') + data['rateProduct']) + '。'))) (await conversation.say((((((((((((((((((((((((((((((('@' + msg.talker().name) + ' ') + data['ownerName']) + ',您好!您的爱车') + data['plateNumber']) + '预计估价共计') + data['totalPremium']) + '元,其中交强险') + data['compulsoryPremium']) + '元, 商业险') + data['businessPremium']) + '元。商业险明细:车损保额') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('车损' in a['name'])][0]['premium']) + '元 ;三者保额') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('三者' in a['name'])][0]['premium']) + '元 ;司机保额') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('司机' in a['name'])][0]['premium']) + '元;乘客保额') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['amountWy']) + '万元,保费') + [a for a in data['policyBusinessCategoryList'] if ('乘客' in a['name'])][0]['premium']) + '元 。代收车船税') + data['taxPremium']) + '元。此报价仅供参考,最终价格以出单为准。'))) file_box = FileBox.from_url(data['url'], name='policy.jpg') (await conversation.say(file_box)) return except: (await conversation.say((('@' + msg.talker().name) + ' 操作报价失败,请手动操作!'))) return return num = (num + 1) elif (msg_type == MessageType.MESSAGE_TYPE_IMAGE): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info('receving image file') image: WeImage = msg.to_image() hd_file_box: FileBox = (await image.hd()) url = (ip + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': ((str(int(time.time())) + '.jpg'), BytesIO(hd_file_box.stream), 'image/jpeg'), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) else: pass if (msg.type() == MessageType.MESSAGE_TYPE_UNSPECIFIED): talker = msg.talker() assert isinstance(talker, Contact) elif ('21121012651@chatroom' == room_id): if (('@AI出单' in text) and ('查单' in text)): pass elif (('@AI出单' in text) and ('批量出单' in text)): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) (await conversation.say((('@' + msg.talker().name) + ' 收到指令,努力处理中请稍后!'))) url = (ip_js + 'api/RobotApi/wycPolicy.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'operator': msg.talker().name, 'cmdName': text, 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return res_dict = json.loads(response.text) if (res_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) return num = 0 second = sleep_time(0, 0, 5) while True: time.sleep(second) url = (ip_js + 'api/RobotApi/pullPolicy.do') multipart_encoder = MultipartEncoder(fields={'uuid': res_dict['data'], 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} try: response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) except: if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return response_dict = json.loads(response.text) if (response_dict['errorCode'] != ): (await conversation.say((('@' + msg.talker().name) + response_dict['errorMsg']))) return if (num == 6): (await conversation.say((('@' + msg.talker().name) + ' 抱歉,连接已断开,未查询到用户数据!'))) return elif response_dict['success']: try: file_box = FileBox.from_url(response_dict['data'], name='policy.xlsx') (await conversation.say(file_box)) (await conversation.say((('@' + msg.talker().name) + ' 完成批量出单,请查收结果!'))) return except: (await conversation.say((('@' + msg.talker().name) + ' 批量出单失败,请手动操作!'))) return num = (num + 1) elif (msg_type == MessageType.MESSAGE_TYPE_IMAGE): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info('receving image file') image: WeImage = msg.to_image() hd_file_box: FileBox = (await image.hd()) url = (ip_js + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': ((str(int(time.time())) + '.jpg'), BytesIO(hd_file_box.stream), 'image/jpeg'), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) elif (msg_type in [MessageType.MESSAGE_TYPE_AUDIO, MessageType.MESSAGE_TYPE_ATTACHMENT, MessageType.MESSAGE_TYPE_VIDEO]): conversation: Union[(Room, Contact)] = (from_contact if (room is None) else room) (await conversation.ready()) logger.info(('receving file:' + 'test')) file_box = (await msg.to_file_box()) url = (ip_js + 'api/RobotApi/imgUpload.do') multipart_encoder = MultipartEncoder(fields={'roomId': room_id, 'operator': '6', 'nickname': msg.talker().name, 'contactId': contact_id, 'path': '/img/robotOrder', 'storageServer': 'FASTDFS', 'file': (((str(int(time.time())) + '.xlsx') if file_box.name.endswith('xlsx') else '.xls'), BytesIO(file_box.stream), ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' if file_box.name.endswith('xlsx') else 'application/vnd.ms-excel')), 'appKey': 'X08ASKYS'}, boundary=('-----------------------------' + str(random.randint(1e+28, (1e+29 - 1))))) headers = {'Referer': url, 'Content-Type': multipart_encoder.content_type} response = requests.post(url, data=multipart_encoder, headers=headers, timeout=30) res_dict = json.loads(response.text) if (not res_dict['success']): (await conversation.say((('@' + msg.talker().name) + res_dict['errorMsg']))) else: pass if (msg.type() == MessageType.MESSAGE_TYPE_UNSPECIFIED): talker = msg.talker() assert isinstance(talker, Contact) else: pass<|docstring|>listen for message event<|endoftext|>
dc05a2547f26c46ace2e904e215aae6695b6865accb92e279943c0fd5e74e27d
async def on_login(self, contact: Contact) -> None: 'login event\n\n Args:\n contact (Contact): the account logined\n ' logger.info('Contact<%s> has logined ...', contact) self.login_user = contact
login event Args: contact (Contact): the account logined
app/robot.py
on_login
anonier/python-wechaty
0
python
async def on_login(self, contact: Contact) -> None: 'login event\n\n Args:\n contact (Contact): the account logined\n ' logger.info('Contact<%s> has logined ...', contact) self.login_user = contact
async def on_login(self, contact: Contact) -> None: 'login event\n\n Args:\n contact (Contact): the account logined\n ' logger.info('Contact<%s> has logined ...', contact) self.login_user = contact<|docstring|>login event Args: contact (Contact): the account logined<|endoftext|>
f55b4b6c4afae17ea0528d55353ec6c858062cdd820ad0a5164062ebd0adbb32
async def on_friendship(self, friendship: Friendship) -> None: 'when receive a new friendship application, or accept a new friendship\n\n Args:\n friendship (Friendship): contains the status and friendship info,\n eg: hello text, friend contact object\n ' MAX_ROOM_MEMBER_COUNT = 500 if (friendship.type() == FriendshipType.FRIENDSHIP_TYPE_RECEIVE): hello_text: str = friendship.hello() if ('wechaty' in hello_text.lower()): (await friendship.accept()) elif (friendship.type() == FriendshipType.FRIENDSHIP_TYPE_CONFIRM): wechaty_rooms: List[Room] = (await self.Room.find_all('Wechaty')) for wechaty_room in wechaty_rooms: members: List[Contact] = (await wechaty_room.member_list()) if (len(members) < MAX_ROOM_MEMBER_COUNT): contact: Contact = friendship.contact() (await wechaty_room.add(contact)) break
when receive a new friendship application, or accept a new friendship Args: friendship (Friendship): contains the status and friendship info, eg: hello text, friend contact object
app/robot.py
on_friendship
anonier/python-wechaty
0
python
async def on_friendship(self, friendship: Friendship) -> None: 'when receive a new friendship application, or accept a new friendship\n\n Args:\n friendship (Friendship): contains the status and friendship info,\n eg: hello text, friend contact object\n ' MAX_ROOM_MEMBER_COUNT = 500 if (friendship.type() == FriendshipType.FRIENDSHIP_TYPE_RECEIVE): hello_text: str = friendship.hello() if ('wechaty' in hello_text.lower()): (await friendship.accept()) elif (friendship.type() == FriendshipType.FRIENDSHIP_TYPE_CONFIRM): wechaty_rooms: List[Room] = (await self.Room.find_all('Wechaty')) for wechaty_room in wechaty_rooms: members: List[Contact] = (await wechaty_room.member_list()) if (len(members) < MAX_ROOM_MEMBER_COUNT): contact: Contact = friendship.contact() (await wechaty_room.add(contact)) break
async def on_friendship(self, friendship: Friendship) -> None: 'when receive a new friendship application, or accept a new friendship\n\n Args:\n friendship (Friendship): contains the status and friendship info,\n eg: hello text, friend contact object\n ' MAX_ROOM_MEMBER_COUNT = 500 if (friendship.type() == FriendshipType.FRIENDSHIP_TYPE_RECEIVE): hello_text: str = friendship.hello() if ('wechaty' in hello_text.lower()): (await friendship.accept()) elif (friendship.type() == FriendshipType.FRIENDSHIP_TYPE_CONFIRM): wechaty_rooms: List[Room] = (await self.Room.find_all('Wechaty')) for wechaty_room in wechaty_rooms: members: List[Contact] = (await wechaty_room.member_list()) if (len(members) < MAX_ROOM_MEMBER_COUNT): contact: Contact = friendship.contact() (await wechaty_room.add(contact)) break<|docstring|>when receive a new friendship application, or accept a new friendship Args: friendship (Friendship): contains the status and friendship info, eg: hello text, friend contact object<|endoftext|>
23fbd86be74651120140609606097505b80dc8e74d1f9dd9b509ed034ad056f4
async def on_room_join(self, room: Room, invitees: List[Contact], inviter: Contact, date: datetime) -> None: 'on_room_join when there are new contacts to the room\n\n Args:\n room (Room): the room instance\n invitees (List[Contact]): the new contacts to the room\n inviter (Contact): the inviter who share qrcode or manual invite someone\n date (datetime): the datetime to join the room\n ' names: List[str] = [] for invitee in invitees: (await invitee.ready()) names.append(invitee.name) (await room.say(f"welcome {','.join(names)} to the wechaty group !"))
on_room_join when there are new contacts to the room Args: room (Room): the room instance invitees (List[Contact]): the new contacts to the room inviter (Contact): the inviter who share qrcode or manual invite someone date (datetime): the datetime to join the room
app/robot.py
on_room_join
anonier/python-wechaty
0
python
async def on_room_join(self, room: Room, invitees: List[Contact], inviter: Contact, date: datetime) -> None: 'on_room_join when there are new contacts to the room\n\n Args:\n room (Room): the room instance\n invitees (List[Contact]): the new contacts to the room\n inviter (Contact): the inviter who share qrcode or manual invite someone\n date (datetime): the datetime to join the room\n ' names: List[str] = [] for invitee in invitees: (await invitee.ready()) names.append(invitee.name) (await room.say(f"welcome {','.join(names)} to the wechaty group !"))
async def on_room_join(self, room: Room, invitees: List[Contact], inviter: Contact, date: datetime) -> None: 'on_room_join when there are new contacts to the room\n\n Args:\n room (Room): the room instance\n invitees (List[Contact]): the new contacts to the room\n inviter (Contact): the inviter who share qrcode or manual invite someone\n date (datetime): the datetime to join the room\n ' names: List[str] = [] for invitee in invitees: (await invitee.ready()) names.append(invitee.name) (await room.say(f"welcome {','.join(names)} to the wechaty group !"))<|docstring|>on_room_join when there are new contacts to the room Args: room (Room): the room instance invitees (List[Contact]): the new contacts to the room inviter (Contact): the inviter who share qrcode or manual invite someone date (datetime): the datetime to join the room<|endoftext|>
daa3a56170d6ff41cdd90ca9db5588d36f479d2472de480af65c121f384d73d8
def solve_and_print_example(): '\n Example ILP problem solved with PuLP and default CBC solver.\n Problem:\n Minimize x + y (first integers, then real numbers) with constraints:\n y >= x - 1\n y >= -4x + 4\n y <= -0.5x + 3\n '
Example ILP problem solved with PuLP and default CBC solver. Problem: Minimize x + y (first integers, then real numbers) with constraints: y >= x - 1 y >= -4x + 4 y <= -0.5x + 3
lab6_ILP/ilp/example.py
solve_and_print_example
j-adamczyk/ADPTO_templates
0
python
def solve_and_print_example(): '\n Example ILP problem solved with PuLP and default CBC solver.\n Problem:\n Minimize x + y (first integers, then real numbers) with constraints:\n y >= x - 1\n y >= -4x + 4\n y <= -0.5x + 3\n '
def solve_and_print_example(): '\n Example ILP problem solved with PuLP and default CBC solver.\n Problem:\n Minimize x + y (first integers, then real numbers) with constraints:\n y >= x - 1\n y >= -4x + 4\n y <= -0.5x + 3\n '<|docstring|>Example ILP problem solved with PuLP and default CBC solver. Problem: Minimize x + y (first integers, then real numbers) with constraints: y >= x - 1 y >= -4x + 4 y <= -0.5x + 3<|endoftext|>
654f4f05efd1e5f681cee7c84ef501b3dd8e5cdc5bca942eb33f9bf6bdc6fd15
@click.command() @click.argument('data_filepath', type=click.Path(), default='data') @click.argument('trained_model_filepath', type=click.Path(), default='models/trained_model.pth') def main(data_filepath, trained_model_filepath): ' Evaluates the neural network using MNIST test data ' logger = logging.getLogger(__name__) logger.info('Evaluating a neural network using MNIST test data') model = MyAwesomeModel() project_dir = Path(__file__).resolve().parents[2] state_dict = torch.load(project_dir.joinpath(trained_model_filepath)) model.load_state_dict(state_dict) transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) test_set = datasets.MNIST(project_dir.joinpath(data_filepath), download=False, train=False, transform=transform) batch_size = 64 test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=True) test_correct = 0 with torch.no_grad(): model.eval() for (images, labels) in test_loader: log_ps = model(images) ps = torch.exp(log_ps) (top_p, top_class) = ps.topk(1, dim=1) equals = (top_class == labels.view(*top_class.shape)) test_correct += equals.type(torch.FloatTensor).sum().item() test_accuracy = (test_correct / len(test_set)) logger.info(str('Test Accuracy: {:.3f}'.format(test_accuracy)))
Evaluates the neural network using MNIST test data
src/models/evaluate_model.py
main
georgezefko/https---github.com-georgezefko-MLOps_dtu
0
python
@click.command() @click.argument('data_filepath', type=click.Path(), default='data') @click.argument('trained_model_filepath', type=click.Path(), default='models/trained_model.pth') def main(data_filepath, trained_model_filepath): ' ' logger = logging.getLogger(__name__) logger.info('Evaluating a neural network using MNIST test data') model = MyAwesomeModel() project_dir = Path(__file__).resolve().parents[2] state_dict = torch.load(project_dir.joinpath(trained_model_filepath)) model.load_state_dict(state_dict) transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) test_set = datasets.MNIST(project_dir.joinpath(data_filepath), download=False, train=False, transform=transform) batch_size = 64 test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=True) test_correct = 0 with torch.no_grad(): model.eval() for (images, labels) in test_loader: log_ps = model(images) ps = torch.exp(log_ps) (top_p, top_class) = ps.topk(1, dim=1) equals = (top_class == labels.view(*top_class.shape)) test_correct += equals.type(torch.FloatTensor).sum().item() test_accuracy = (test_correct / len(test_set)) logger.info(str('Test Accuracy: {:.3f}'.format(test_accuracy)))
@click.command() @click.argument('data_filepath', type=click.Path(), default='data') @click.argument('trained_model_filepath', type=click.Path(), default='models/trained_model.pth') def main(data_filepath, trained_model_filepath): ' ' logger = logging.getLogger(__name__) logger.info('Evaluating a neural network using MNIST test data') model = MyAwesomeModel() project_dir = Path(__file__).resolve().parents[2] state_dict = torch.load(project_dir.joinpath(trained_model_filepath)) model.load_state_dict(state_dict) transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) test_set = datasets.MNIST(project_dir.joinpath(data_filepath), download=False, train=False, transform=transform) batch_size = 64 test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=True) test_correct = 0 with torch.no_grad(): model.eval() for (images, labels) in test_loader: log_ps = model(images) ps = torch.exp(log_ps) (top_p, top_class) = ps.topk(1, dim=1) equals = (top_class == labels.view(*top_class.shape)) test_correct += equals.type(torch.FloatTensor).sum().item() test_accuracy = (test_correct / len(test_set)) logger.info(str('Test Accuracy: {:.3f}'.format(test_accuracy)))<|docstring|>Evaluates the neural network using MNIST test data<|endoftext|>
c9d1e0f3bc64d89f8c50dc2f56facd94faf9c624220259a6e5f66a65d1adb266
def plane_phase(self, period, theta): '\n Compute a plane wave phase with a specified angle with the horizontal. This gets represented in the tilt of the\n fringes produced.\n :return: numpy array with the phase\n ' (u, v) = np.meshgrid((np.linspace(0, self.width, self.width, endpoint=False) + (1 / 2)), (np.linspace(0, self.height, self.height, endpoint=False) + (1 / 2))) phase = ((u * np.round(np.cos(theta), decimals=2)) + (v * np.round(np.sin(theta), decimals=2))) return (((2.0 * math.pi) / period) * phase)
Compute a plane wave phase with a specified angle with the horizontal. This gets represented in the tilt of the fringes produced. :return: numpy array with the phase
speck_rem/dmd.py
plane_phase
johnrest/speckle_removal
0
python
def plane_phase(self, period, theta): '\n Compute a plane wave phase with a specified angle with the horizontal. This gets represented in the tilt of the\n fringes produced.\n :return: numpy array with the phase\n ' (u, v) = np.meshgrid((np.linspace(0, self.width, self.width, endpoint=False) + (1 / 2)), (np.linspace(0, self.height, self.height, endpoint=False) + (1 / 2))) phase = ((u * np.round(np.cos(theta), decimals=2)) + (v * np.round(np.sin(theta), decimals=2))) return (((2.0 * math.pi) / period) * phase)
def plane_phase(self, period, theta): '\n Compute a plane wave phase with a specified angle with the horizontal. This gets represented in the tilt of the\n fringes produced.\n :return: numpy array with the phase\n ' (u, v) = np.meshgrid((np.linspace(0, self.width, self.width, endpoint=False) + (1 / 2)), (np.linspace(0, self.height, self.height, endpoint=False) + (1 / 2))) phase = ((u * np.round(np.cos(theta), decimals=2)) + (v * np.round(np.sin(theta), decimals=2))) return (((2.0 * math.pi) / period) * phase)<|docstring|>Compute a plane wave phase with a specified angle with the horizontal. This gets represented in the tilt of the fringes produced. :return: numpy array with the phase<|endoftext|>
383922a7be445879da61a56d7bf0c592eab937189e8afe553e66ecc86cc65ee7
def compute_plane_mask(self, period, theta): '\n Compute the mask for a tilted plane with an specific frequency and rotation\n :param period: in pixels\n :param theta: angle in radians\n :return: None\n ' phase = self.plane_phase(period, theta) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin(phase))))
Compute the mask for a tilted plane with an specific frequency and rotation :param period: in pixels :param theta: angle in radians :return: None
speck_rem/dmd.py
compute_plane_mask
johnrest/speckle_removal
0
python
def compute_plane_mask(self, period, theta): '\n Compute the mask for a tilted plane with an specific frequency and rotation\n :param period: in pixels\n :param theta: angle in radians\n :return: None\n ' phase = self.plane_phase(period, theta) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin(phase))))
def compute_plane_mask(self, period, theta): '\n Compute the mask for a tilted plane with an specific frequency and rotation\n :param period: in pixels\n :param theta: angle in radians\n :return: None\n ' phase = self.plane_phase(period, theta) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin(phase))))<|docstring|>Compute the mask for a tilted plane with an specific frequency and rotation :param period: in pixels :param theta: angle in radians :return: None<|endoftext|>
bb4d403d6256029e055d936ee7eecd6d033f64338bbe64c900fbb3be0119c9b4
def compute_fairness_constraint_mask(self, period, theta, pattern, grain): '\n Compute a random mask under the fairness constraint sampling with a specified block/grain size\n :param period: in pixels\n :param theta: angle in radians\n :param pattern: numpy array with the sampling under fcn generated from another function\n :param grain: size of individual elements in pixels\n :return: None\n ' phase = self.plane_phase(period, theta) large_pattern = pattern.repeat(grain, axis=0).repeat(grain, axis=1) large_pattern = np.pad(large_pattern, ((28, 28), (448, 448)), 'constant', constant_values=0) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin((phase - (large_pattern * np.pi))))))
Compute a random mask under the fairness constraint sampling with a specified block/grain size :param period: in pixels :param theta: angle in radians :param pattern: numpy array with the sampling under fcn generated from another function :param grain: size of individual elements in pixels :return: None
speck_rem/dmd.py
compute_fairness_constraint_mask
johnrest/speckle_removal
0
python
def compute_fairness_constraint_mask(self, period, theta, pattern, grain): '\n Compute a random mask under the fairness constraint sampling with a specified block/grain size\n :param period: in pixels\n :param theta: angle in radians\n :param pattern: numpy array with the sampling under fcn generated from another function\n :param grain: size of individual elements in pixels\n :return: None\n ' phase = self.plane_phase(period, theta) large_pattern = pattern.repeat(grain, axis=0).repeat(grain, axis=1) large_pattern = np.pad(large_pattern, ((28, 28), (448, 448)), 'constant', constant_values=0) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin((phase - (large_pattern * np.pi))))))
def compute_fairness_constraint_mask(self, period, theta, pattern, grain): '\n Compute a random mask under the fairness constraint sampling with a specified block/grain size\n :param period: in pixels\n :param theta: angle in radians\n :param pattern: numpy array with the sampling under fcn generated from another function\n :param grain: size of individual elements in pixels\n :return: None\n ' phase = self.plane_phase(period, theta) large_pattern = pattern.repeat(grain, axis=0).repeat(grain, axis=1) large_pattern = np.pad(large_pattern, ((28, 28), (448, 448)), 'constant', constant_values=0) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin((phase - (large_pattern * np.pi))))))<|docstring|>Compute a random mask under the fairness constraint sampling with a specified block/grain size :param period: in pixels :param theta: angle in radians :param pattern: numpy array with the sampling under fcn generated from another function :param grain: size of individual elements in pixels :return: None<|endoftext|>
2bdb066d0b4402c2eb207277643c8c2044b0cfdd89868c4095f422099185a856
def compute_random_mask(self, period, theta, grain): '\n Compute a random mask with a specified block/grain size\n :param period: in pixels\n :param theta: angle in radians\n :param grain: size of individual elements in pixels\n :return: None\n ' phase = self.plane_phase(period, theta) window = int(np.ceil((1080 / grain))) pattern = np.random.randint(2, size=(window, window)) large_pattern = pattern.repeat(grain, axis=0).repeat(grain, axis=1) large_pattern = large_pattern[(0:1080, 0:1080)] large_pattern = np.pad(large_pattern, ((0, 0), (420, 420)), 'constant', constant_values=0) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin((phase - (large_pattern * np.pi))))))
Compute a random mask with a specified block/grain size :param period: in pixels :param theta: angle in radians :param grain: size of individual elements in pixels :return: None
speck_rem/dmd.py
compute_random_mask
johnrest/speckle_removal
0
python
def compute_random_mask(self, period, theta, grain): '\n Compute a random mask with a specified block/grain size\n :param period: in pixels\n :param theta: angle in radians\n :param grain: size of individual elements in pixels\n :return: None\n ' phase = self.plane_phase(period, theta) window = int(np.ceil((1080 / grain))) pattern = np.random.randint(2, size=(window, window)) large_pattern = pattern.repeat(grain, axis=0).repeat(grain, axis=1) large_pattern = large_pattern[(0:1080, 0:1080)] large_pattern = np.pad(large_pattern, ((0, 0), (420, 420)), 'constant', constant_values=0) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin((phase - (large_pattern * np.pi))))))
def compute_random_mask(self, period, theta, grain): '\n Compute a random mask with a specified block/grain size\n :param period: in pixels\n :param theta: angle in radians\n :param grain: size of individual elements in pixels\n :return: None\n ' phase = self.plane_phase(period, theta) window = int(np.ceil((1080 / grain))) pattern = np.random.randint(2, size=(window, window)) large_pattern = pattern.repeat(grain, axis=0).repeat(grain, axis=1) large_pattern = large_pattern[(0:1080, 0:1080)] large_pattern = np.pad(large_pattern, ((0, 0), (420, 420)), 'constant', constant_values=0) self.image_array = ((1 / 2) + ((1 / 2) * np.sign(np.sin((phase - (large_pattern * np.pi))))))<|docstring|>Compute a random mask with a specified block/grain size :param period: in pixels :param theta: angle in radians :param grain: size of individual elements in pixels :return: None<|endoftext|>
002cff82b7b531b126af88ef20f6eb535aa294e193c75bcbf8c386ffdd084525
def __init__(self, host: str, timeout: Union[(float, Timeout, None)]=None): 'Instantiate connection to UNIX domain socket for HTTP client.' if isinstance(timeout, Timeout): try: timeout = float(timeout.total) except TypeError: timeout = None super().__init__('localhost', timeout=timeout) self.url = host self.sock: Optional[socket.socket] = None self.timeout = timeout
Instantiate connection to UNIX domain socket for HTTP client.
podman/api/uds.py
__init__
FedericoRessi/podman-py
0
python
def __init__(self, host: str, timeout: Union[(float, Timeout, None)]=None): if isinstance(timeout, Timeout): try: timeout = float(timeout.total) except TypeError: timeout = None super().__init__('localhost', timeout=timeout) self.url = host self.sock: Optional[socket.socket] = None self.timeout = timeout
def __init__(self, host: str, timeout: Union[(float, Timeout, None)]=None): if isinstance(timeout, Timeout): try: timeout = float(timeout.total) except TypeError: timeout = None super().__init__('localhost', timeout=timeout) self.url = host self.sock: Optional[socket.socket] = None self.timeout = timeout<|docstring|>Instantiate connection to UNIX domain socket for HTTP client.<|endoftext|>
bbbc58e61762624452d1bdc1d29f5d33328d9dbe95348738691099fda8e73e74
def connect(self): 'Returns socket for unix domain socket.' sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.timeout) netloc = unquote(urlparse(self.url).netloc) sock.connect(netloc) self.sock = sock
Returns socket for unix domain socket.
podman/api/uds.py
connect
FedericoRessi/podman-py
0
python
def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.timeout) netloc = unquote(urlparse(self.url).netloc) sock.connect(netloc) self.sock = sock
def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.timeout) netloc = unquote(urlparse(self.url).netloc) sock.connect(netloc) self.sock = sock<|docstring|>Returns socket for unix domain socket.<|endoftext|>
108e48e76fbc0ccb346d603128597b7d6eb357ef7e3f4f10f36ef0a69c2f0960
def __del__(self): 'Cleanup connection.' if self.sock: self.sock.close()
Cleanup connection.
podman/api/uds.py
__del__
FedericoRessi/podman-py
0
python
def __del__(self): if self.sock: self.sock.close()
def __del__(self): if self.sock: self.sock.close()<|docstring|>Cleanup connection.<|endoftext|>
b913ac0dafe9bb737d34436e21c992e57732a6b5a4451ce64b7d95126a69f2f7
def reduce_maze(maze): '\n This function returns a adjacency matrix representing the tree-like structure of the\n maze.\n\n It only contains the initial position(s), the keys and the doors.\n\n There is an edge between 2 given vertices x and y, iff one can go from x to y in the\n maze without passing through another key / door.\n\n This function is mainly used to quickly figure out which keys are accessible or not.\n ' q = deque() seen = set() for i in range(len(maze)): for j in range(len(maze[0])): if (maze[i][j] in ['@', '1', '2', '3', '4']): q.append(((i, j), None)) seen.add((i, j)) reduced_maze = defaultdict(set) while q: (pos, pred) = q.popleft() current = maze[pos[0]][pos[1]] if (current not in ['#', '.']): if (pred is not None): reduced_maze[pred].add(current) reduced_maze[current].add(pred) pred = current for next_pos in next_positions(pos): if ((maze[next_pos[0]][next_pos[1]] == '#') or (next_pos in seen)): continue seen.add(next_pos) q.append((next_pos, pred)) return dict(reduced_maze)
This function returns a adjacency matrix representing the tree-like structure of the maze. It only contains the initial position(s), the keys and the doors. There is an edge between 2 given vertices x and y, iff one can go from x to y in the maze without passing through another key / door. This function is mainly used to quickly figure out which keys are accessible or not.
day-18/part-2/francisco.py
reduce_maze
TPXP/adventofcode-2019
8
python
def reduce_maze(maze): '\n This function returns a adjacency matrix representing the tree-like structure of the\n maze.\n\n It only contains the initial position(s), the keys and the doors.\n\n There is an edge between 2 given vertices x and y, iff one can go from x to y in the\n maze without passing through another key / door.\n\n This function is mainly used to quickly figure out which keys are accessible or not.\n ' q = deque() seen = set() for i in range(len(maze)): for j in range(len(maze[0])): if (maze[i][j] in ['@', '1', '2', '3', '4']): q.append(((i, j), None)) seen.add((i, j)) reduced_maze = defaultdict(set) while q: (pos, pred) = q.popleft() current = maze[pos[0]][pos[1]] if (current not in ['#', '.']): if (pred is not None): reduced_maze[pred].add(current) reduced_maze[current].add(pred) pred = current for next_pos in next_positions(pos): if ((maze[next_pos[0]][next_pos[1]] == '#') or (next_pos in seen)): continue seen.add(next_pos) q.append((next_pos, pred)) return dict(reduced_maze)
def reduce_maze(maze): '\n This function returns a adjacency matrix representing the tree-like structure of the\n maze.\n\n It only contains the initial position(s), the keys and the doors.\n\n There is an edge between 2 given vertices x and y, iff one can go from x to y in the\n maze without passing through another key / door.\n\n This function is mainly used to quickly figure out which keys are accessible or not.\n ' q = deque() seen = set() for i in range(len(maze)): for j in range(len(maze[0])): if (maze[i][j] in ['@', '1', '2', '3', '4']): q.append(((i, j), None)) seen.add((i, j)) reduced_maze = defaultdict(set) while q: (pos, pred) = q.popleft() current = maze[pos[0]][pos[1]] if (current not in ['#', '.']): if (pred is not None): reduced_maze[pred].add(current) reduced_maze[current].add(pred) pred = current for next_pos in next_positions(pos): if ((maze[next_pos[0]][next_pos[1]] == '#') or (next_pos in seen)): continue seen.add(next_pos) q.append((next_pos, pred)) return dict(reduced_maze)<|docstring|>This function returns a adjacency matrix representing the tree-like structure of the maze. It only contains the initial position(s), the keys and the doors. There is an edge between 2 given vertices x and y, iff one can go from x to y in the maze without passing through another key / door. This function is mainly used to quickly figure out which keys are accessible or not.<|endoftext|>
b5bf948db15c1c5cb67f71b2b1fa566650d61c11eeffa03ba31171b87779c5e3
def get_accessible_keys(reduced_maze, keys, pos='@'): '\n Uses the reduced maze to quickly figure out which keys are accessible from a given\n position.\n ' q = deque([pos]) seen = set() accessible = set() while q: pos = q.popleft() if (pos in ascii_lowercase): accessible.add(pos) for next_pos in reduced_maze[pos]: if (next_pos in seen): continue seen.add(next_pos) if ((next_pos in ascii_uppercase) and (next_pos.lower() in reduced_maze) and (next_pos.lower() not in keys)): continue q.append(next_pos) return accessible
Uses the reduced maze to quickly figure out which keys are accessible from a given position.
day-18/part-2/francisco.py
get_accessible_keys
TPXP/adventofcode-2019
8
python
def get_accessible_keys(reduced_maze, keys, pos='@'): '\n Uses the reduced maze to quickly figure out which keys are accessible from a given\n position.\n ' q = deque([pos]) seen = set() accessible = set() while q: pos = q.popleft() if (pos in ascii_lowercase): accessible.add(pos) for next_pos in reduced_maze[pos]: if (next_pos in seen): continue seen.add(next_pos) if ((next_pos in ascii_uppercase) and (next_pos.lower() in reduced_maze) and (next_pos.lower() not in keys)): continue q.append(next_pos) return accessible
def get_accessible_keys(reduced_maze, keys, pos='@'): '\n Uses the reduced maze to quickly figure out which keys are accessible from a given\n position.\n ' q = deque([pos]) seen = set() accessible = set() while q: pos = q.popleft() if (pos in ascii_lowercase): accessible.add(pos) for next_pos in reduced_maze[pos]: if (next_pos in seen): continue seen.add(next_pos) if ((next_pos in ascii_uppercase) and (next_pos.lower() in reduced_maze) and (next_pos.lower() not in keys)): continue q.append(next_pos) return accessible<|docstring|>Uses the reduced maze to quickly figure out which keys are accessible from a given position.<|endoftext|>
95f7abc646eb5cc38c8ece5f59c1fc0c3a190b456c2fbf77db0e7f652bed74f4
def compute_distances(maze): '\n Returns a matrix of distances between all the points of interest.\n d[x][y] is the distance of the only path that goes from x to y by only passing\n through keys and doors.\n ' positions = {} for i in range(len(maze)): for j in range(len(maze[0])): if ((maze[i][j] == '@') or (maze[i][j] in ascii_lowercase)): positions[maze[i][j]] = (i, j) def bfs(pos): q = deque([(pos, 0)]) seen = {pos} distances = {} while q: (pos, distance) = q.popleft() current = maze[pos[0]][pos[1]] if ((current not in ['#', '.']) and (not current.isupper())): distances[current] = distance for next_pos in next_positions(pos): if (maze[next_pos[0]][next_pos[1]] == '#'): continue if (next_pos in seen): continue seen.add(next_pos) q.append((next_pos, (distance + 1))) return distances return (positions, {key: bfs(pos) for (key, pos) in positions.items()})
Returns a matrix of distances between all the points of interest. d[x][y] is the distance of the only path that goes from x to y by only passing through keys and doors.
day-18/part-2/francisco.py
compute_distances
TPXP/adventofcode-2019
8
python
def compute_distances(maze): '\n Returns a matrix of distances between all the points of interest.\n d[x][y] is the distance of the only path that goes from x to y by only passing\n through keys and doors.\n ' positions = {} for i in range(len(maze)): for j in range(len(maze[0])): if ((maze[i][j] == '@') or (maze[i][j] in ascii_lowercase)): positions[maze[i][j]] = (i, j) def bfs(pos): q = deque([(pos, 0)]) seen = {pos} distances = {} while q: (pos, distance) = q.popleft() current = maze[pos[0]][pos[1]] if ((current not in ['#', '.']) and (not current.isupper())): distances[current] = distance for next_pos in next_positions(pos): if (maze[next_pos[0]][next_pos[1]] == '#'): continue if (next_pos in seen): continue seen.add(next_pos) q.append((next_pos, (distance + 1))) return distances return (positions, {key: bfs(pos) for (key, pos) in positions.items()})
def compute_distances(maze): '\n Returns a matrix of distances between all the points of interest.\n d[x][y] is the distance of the only path that goes from x to y by only passing\n through keys and doors.\n ' positions = {} for i in range(len(maze)): for j in range(len(maze[0])): if ((maze[i][j] == '@') or (maze[i][j] in ascii_lowercase)): positions[maze[i][j]] = (i, j) def bfs(pos): q = deque([(pos, 0)]) seen = {pos} distances = {} while q: (pos, distance) = q.popleft() current = maze[pos[0]][pos[1]] if ((current not in ['#', '.']) and (not current.isupper())): distances[current] = distance for next_pos in next_positions(pos): if (maze[next_pos[0]][next_pos[1]] == '#'): continue if (next_pos in seen): continue seen.add(next_pos) q.append((next_pos, (distance + 1))) return distances return (positions, {key: bfs(pos) for (key, pos) in positions.items()})<|docstring|>Returns a matrix of distances between all the points of interest. d[x][y] is the distance of the only path that goes from x to y by only passing through keys and doors.<|endoftext|>
e85f3ecc620a8433a3c9615af96a76293a90978cd96926df01796849414aac54
def __init__(self, gamma=1.0, offset=0, lower_bound=0): '\n :param float gamma: the root for gamma computation\n :param float offset: an offset added to the result\n :param int lower_bound: The lowest possible output value - the highest\n is always 255.\n\n ' self.gamma = gamma self.offset = offset self.lower_bound = lower_bound width = (255 - lower_bound) def gam(i): return int(((lower_bound + (pow((i / 255), gamma) * width)) + offset)) self.table = tuple((gam(i) for i in range(256)))
:param float gamma: the root for gamma computation :param float offset: an offset added to the result :param int lower_bound: The lowest possible output value - the highest is always 255.
bibliopixel/colors/gamma.py
__init__
8cH9azbsFifZ/BiblioPixel
2
python
def __init__(self, gamma=1.0, offset=0, lower_bound=0): '\n :param float gamma: the root for gamma computation\n :param float offset: an offset added to the result\n :param int lower_bound: The lowest possible output value - the highest\n is always 255.\n\n ' self.gamma = gamma self.offset = offset self.lower_bound = lower_bound width = (255 - lower_bound) def gam(i): return int(((lower_bound + (pow((i / 255), gamma) * width)) + offset)) self.table = tuple((gam(i) for i in range(256)))
def __init__(self, gamma=1.0, offset=0, lower_bound=0): '\n :param float gamma: the root for gamma computation\n :param float offset: an offset added to the result\n :param int lower_bound: The lowest possible output value - the highest\n is always 255.\n\n ' self.gamma = gamma self.offset = offset self.lower_bound = lower_bound width = (255 - lower_bound) def gam(i): return int(((lower_bound + (pow((i / 255), gamma) * width)) + offset)) self.table = tuple((gam(i) for i in range(256)))<|docstring|>:param float gamma: the root for gamma computation :param float offset: an offset added to the result :param int lower_bound: The lowest possible output value - the highest is always 255.<|endoftext|>
46a6dc8e488775e97c16d995518f9121a390a56e5cc0ecd041fd4702cfd0eee8
def get(self, i): '\n :returns: The gamma table entry\n :param int i: the index into the table\n ' return self.table[max(0, min(255, int(i)))]
:returns: The gamma table entry :param int i: the index into the table
bibliopixel/colors/gamma.py
get
8cH9azbsFifZ/BiblioPixel
2
python
def get(self, i): '\n :returns: The gamma table entry\n :param int i: the index into the table\n ' return self.table[max(0, min(255, int(i)))]
def get(self, i): '\n :returns: The gamma table entry\n :param int i: the index into the table\n ' return self.table[max(0, min(255, int(i)))]<|docstring|>:returns: The gamma table entry :param int i: the index into the table<|endoftext|>
b01a7e01d6cc74fab267b7ef65ab5041cf8e6262ecb4592080d3cc11879d8a6e
def hz2mel(f): '\\cite{shannon:2003}' return (np.log10(((f / 700.0) + 1.0)) * 2595.0)
\cite{shannon:2003}
examples/nsgt_orig/fscale.py
hz2mel
sevagh/slicqt
85
python
def hz2mel(f): '\' return (np.log10(((f / 700.0) + 1.0)) * 2595.0)
def hz2mel(f): '\' return (np.log10(((f / 700.0) + 1.0)) * 2595.0)<|docstring|>\cite{shannon:2003}<|endoftext|>
abeec8d36ab069b3e85ec6ef7093c3b0a6527bea67454f7ef08c8b4343ba28fa
def mel2hz(m): '\\cite{shannon:2003}' return ((np.power(10.0, (m / 2595.0)) - 1.0) * 700.0)
\cite{shannon:2003}
examples/nsgt_orig/fscale.py
mel2hz
sevagh/slicqt
85
python
def mel2hz(m): '\' return ((np.power(10.0, (m / 2595.0)) - 1.0) * 700.0)
def mel2hz(m): '\' return ((np.power(10.0, (m / 2595.0)) - 1.0) * 700.0)<|docstring|>\cite{shannon:2003}<|endoftext|>
e3338b4e1dc6f5be7c11c61d24581ca996c55be7d8a0f34ad124ee0d2ddb9c24
def __init__(self, fmin, fmax, bpo, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bpo: bands per octave (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' lfmin = np.log2(fmin) lfmax = np.log2(fmax) bnds = (int(np.ceil(((lfmax - lfmin) * bpo))) + 1) Scale.__init__(self, (bnds + (beyond * 2))) odiv = ((lfmax - lfmin) / (bnds - 1)) lfmin_ = (lfmin - (odiv * beyond)) lfmax_ = (lfmax + (odiv * beyond)) self.fmin = (2 ** lfmin_) self.fmax = (2 ** lfmax_) self.pow2n = (2 ** odiv) self.q = ((np.sqrt(self.pow2n) / (self.pow2n - 1.0)) / 2.0)
@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bpo: bands per octave (int) @param beyond: number of frequency bands below fmin and above fmax (int)
examples/nsgt_orig/fscale.py
__init__
sevagh/slicqt
85
python
def __init__(self, fmin, fmax, bpo, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bpo: bands per octave (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' lfmin = np.log2(fmin) lfmax = np.log2(fmax) bnds = (int(np.ceil(((lfmax - lfmin) * bpo))) + 1) Scale.__init__(self, (bnds + (beyond * 2))) odiv = ((lfmax - lfmin) / (bnds - 1)) lfmin_ = (lfmin - (odiv * beyond)) lfmax_ = (lfmax + (odiv * beyond)) self.fmin = (2 ** lfmin_) self.fmax = (2 ** lfmax_) self.pow2n = (2 ** odiv) self.q = ((np.sqrt(self.pow2n) / (self.pow2n - 1.0)) / 2.0)
def __init__(self, fmin, fmax, bpo, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bpo: bands per octave (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' lfmin = np.log2(fmin) lfmax = np.log2(fmax) bnds = (int(np.ceil(((lfmax - lfmin) * bpo))) + 1) Scale.__init__(self, (bnds + (beyond * 2))) odiv = ((lfmax - lfmin) / (bnds - 1)) lfmin_ = (lfmin - (odiv * beyond)) lfmax_ = (lfmax + (odiv * beyond)) self.fmin = (2 ** lfmin_) self.fmax = (2 ** lfmax_) self.pow2n = (2 ** odiv) self.q = ((np.sqrt(self.pow2n) / (self.pow2n - 1.0)) / 2.0)<|docstring|>@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bpo: bands per octave (int) @param beyond: number of frequency bands below fmin and above fmax (int)<|endoftext|>
6da26512415854a9b0cc64c43b5fed8caa5d5e9e63928c4c1a561540a816ed19
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' Scale.__init__(self, (bnds + (beyond * 2))) lfmin = np.log2(fmin) lfmax = np.log2(fmax) odiv = ((lfmax - lfmin) / (bnds - 1)) lfmin_ = (lfmin - (odiv * beyond)) lfmax_ = (lfmax + (odiv * beyond)) self.fmin = (2 ** lfmin_) self.fmax = (2 ** lfmax_) self.pow2n = (2 ** odiv) self.q = ((np.sqrt(self.pow2n) / (self.pow2n - 1.0)) / 2.0)
@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bnds: number of frequency bands (int) @param beyond: number of frequency bands below fmin and above fmax (int)
examples/nsgt_orig/fscale.py
__init__
sevagh/slicqt
85
python
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' Scale.__init__(self, (bnds + (beyond * 2))) lfmin = np.log2(fmin) lfmax = np.log2(fmax) odiv = ((lfmax - lfmin) / (bnds - 1)) lfmin_ = (lfmin - (odiv * beyond)) lfmax_ = (lfmax + (odiv * beyond)) self.fmin = (2 ** lfmin_) self.fmax = (2 ** lfmax_) self.pow2n = (2 ** odiv) self.q = ((np.sqrt(self.pow2n) / (self.pow2n - 1.0)) / 2.0)
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' Scale.__init__(self, (bnds + (beyond * 2))) lfmin = np.log2(fmin) lfmax = np.log2(fmax) odiv = ((lfmax - lfmin) / (bnds - 1)) lfmin_ = (lfmin - (odiv * beyond)) lfmax_ = (lfmax + (odiv * beyond)) self.fmin = (2 ** lfmin_) self.fmax = (2 ** lfmax_) self.pow2n = (2 ** odiv) self.q = ((np.sqrt(self.pow2n) / (self.pow2n - 1.0)) / 2.0)<|docstring|>@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bnds: number of frequency bands (int) @param beyond: number of frequency bands below fmin and above fmax (int)<|endoftext|>
08a318a7beb9ea5b7b4bd88148a55db29946dfc6bd7242ecbcfb28f35a7a8d2b
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' self.df = (float((fmax - fmin)) / (bnds - 1)) Scale.__init__(self, (bnds + (beyond * 2))) self.fmin = (float(fmin) - (self.df * beyond)) if (self.fmin <= 0): raise ValueError('Frequencies must be > 0.') self.fmax = (float(fmax) + (self.df * beyond))
@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bnds: number of frequency bands (int) @param beyond: number of frequency bands below fmin and above fmax (int)
examples/nsgt_orig/fscale.py
__init__
sevagh/slicqt
85
python
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' self.df = (float((fmax - fmin)) / (bnds - 1)) Scale.__init__(self, (bnds + (beyond * 2))) self.fmin = (float(fmin) - (self.df * beyond)) if (self.fmin <= 0): raise ValueError('Frequencies must be > 0.') self.fmax = (float(fmax) + (self.df * beyond))
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' self.df = (float((fmax - fmin)) / (bnds - 1)) Scale.__init__(self, (bnds + (beyond * 2))) self.fmin = (float(fmin) - (self.df * beyond)) if (self.fmin <= 0): raise ValueError('Frequencies must be > 0.') self.fmax = (float(fmax) + (self.df * beyond))<|docstring|>@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bnds: number of frequency bands (int) @param beyond: number of frequency bands below fmin and above fmax (int)<|endoftext|>
9649b99eb909c59f53ff37c6ba73ad36d3a3a3a6eb326c2cb142eed6fe4e92d5
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' mmin = hz2mel(fmin) mmax = hz2mel(fmax) Scale.__init__(self, (bnds + (beyond * 2))) self.fmin = float(fmin) self.fmax = float(fmax) self.mbnd = ((mmax - mmin) / (bnds - 1)) self.mmin = (mmin - (self.mbnd * beyond)) self.mmax = (mmax + (self.mbnd * beyond))
@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bnds: number of frequency bands (int) @param beyond: number of frequency bands below fmin and above fmax (int)
examples/nsgt_orig/fscale.py
__init__
sevagh/slicqt
85
python
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' mmin = hz2mel(fmin) mmax = hz2mel(fmax) Scale.__init__(self, (bnds + (beyond * 2))) self.fmin = float(fmin) self.fmax = float(fmax) self.mbnd = ((mmax - mmin) / (bnds - 1)) self.mmin = (mmin - (self.mbnd * beyond)) self.mmax = (mmax + (self.mbnd * beyond))
def __init__(self, fmin, fmax, bnds, beyond=0): '\n @param fmin: minimum frequency (Hz)\n @param fmax: maximum frequency (Hz)\n @param bnds: number of frequency bands (int)\n @param beyond: number of frequency bands below fmin and above fmax (int)\n ' mmin = hz2mel(fmin) mmax = hz2mel(fmax) Scale.__init__(self, (bnds + (beyond * 2))) self.fmin = float(fmin) self.fmax = float(fmax) self.mbnd = ((mmax - mmin) / (bnds - 1)) self.mmin = (mmin - (self.mbnd * beyond)) self.mmax = (mmax + (self.mbnd * beyond))<|docstring|>@param fmin: minimum frequency (Hz) @param fmax: maximum frequency (Hz) @param bnds: number of frequency bands (int) @param beyond: number of frequency bands below fmin and above fmax (int)<|endoftext|>
1711ca71303990e80c08bc310fd20e2cc6d30398081d6989358017855d492ec1
@click.command(options_metavar='[<options>]') @click.option('-v', '--verbose', count=True, help='Output more info (repeatable flag).') @click.option('--raw', is_flag=True, help='Output raw API response.') def status(verbose=0, raw=False, _override={}, _return_parsed=False): 'Describe the current playback session.' res = Spotify.request('me/player', method='GET') if (not res): raise NoPlaybackError if raw: if (verbose >= 0): import json click.echo(json.dumps(res)) return res data = {} data['is_podcast'] = (res['currently_playing_type'] == 'episode') if data['is_podcast']: raise PodcastNotSupported data['is_shuffle'] = res['shuffle_state'] data['repeat_state'] = res['repeat_state'] data['is_playing'] = res['is_playing'] data['device'] = {'name': res['device']['name'], 'type': res['device']['type'], 'volume': res['device']['volume_percent']} item = res['item'] context = parse_context(res['context']) data['music'] = {'context': context, 'track': parse_track(item), 'album': parse_album(item['album']), 'artist': parse_artists(item['artists'])} music = data['music'] music['track']['progress'] = format_duration_ms(res['progress_ms']) if _override: data.update(_override) for key in ['name', 'id', 'url']: music['artist'][key] = music['artist'][(key + 's')][0] music['artist'][('long_' + key)] = ', '.join(music['artist'][(key + 's')]) if (key != 'name'): music['artist'][('long_' + key)] = music['artist'][('long_' + key)].replace(' ', '') playback_status = ('Playing' if data['is_playing'] else 'Paused') playback_options = [] if (data['repeat_state'] == 'track'): playback_options.append('repeat [track]') elif (data['repeat_state'] == 'context'): playback_options.append('repeat') if data['is_shuffle']: playback_options.append('shuffle') playback_str = '' if data['is_playing']: playback_options_str = '{}'.format(('on {}'.format((' and '.join(playback_options) + ', ')) if playback_options else '')) playback_str = '({}{}% volume)'.format(playback_options_str, data['device']['volume']) if _return_parsed: return data if (not verbose): click.echo('{}: {}{}\n {} - {}'.format(playback_status, (' ' if (not data['is_playing']) else ''), music['track']['name'], music['artist']['long_name'], music['album']['name'])) if (verbose >= 1): click.echo('Track {} ({} / {})\nArtist {}\nAlbum {}\nStatus {} {}'.format(music['track']['name'], music['track']['progress'], music['track']['duration'], music['artist']['long_name'], music['album']['name'], playback_status, playback_str)) if (verbose >= 2): click.echo('\nDevice {} ({})\nURL {}'.format(data['device']['name'], data['device']['type'], music['track']['url'])) return
Describe the current playback session.
cli/commands/status.py
status
yeahnope/spotify-cli
73
python
@click.command(options_metavar='[<options>]') @click.option('-v', '--verbose', count=True, help='Output more info (repeatable flag).') @click.option('--raw', is_flag=True, help='Output raw API response.') def status(verbose=0, raw=False, _override={}, _return_parsed=False): res = Spotify.request('me/player', method='GET') if (not res): raise NoPlaybackError if raw: if (verbose >= 0): import json click.echo(json.dumps(res)) return res data = {} data['is_podcast'] = (res['currently_playing_type'] == 'episode') if data['is_podcast']: raise PodcastNotSupported data['is_shuffle'] = res['shuffle_state'] data['repeat_state'] = res['repeat_state'] data['is_playing'] = res['is_playing'] data['device'] = {'name': res['device']['name'], 'type': res['device']['type'], 'volume': res['device']['volume_percent']} item = res['item'] context = parse_context(res['context']) data['music'] = {'context': context, 'track': parse_track(item), 'album': parse_album(item['album']), 'artist': parse_artists(item['artists'])} music = data['music'] music['track']['progress'] = format_duration_ms(res['progress_ms']) if _override: data.update(_override) for key in ['name', 'id', 'url']: music['artist'][key] = music['artist'][(key + 's')][0] music['artist'][('long_' + key)] = ', '.join(music['artist'][(key + 's')]) if (key != 'name'): music['artist'][('long_' + key)] = music['artist'][('long_' + key)].replace(' ', ) playback_status = ('Playing' if data['is_playing'] else 'Paused') playback_options = [] if (data['repeat_state'] == 'track'): playback_options.append('repeat [track]') elif (data['repeat_state'] == 'context'): playback_options.append('repeat') if data['is_shuffle']: playback_options.append('shuffle') playback_str = if data['is_playing']: playback_options_str = '{}'.format(('on {}'.format((' and '.join(playback_options) + ', ')) if playback_options else )) playback_str = '({}{}% volume)'.format(playback_options_str, data['device']['volume']) if _return_parsed: return data if (not verbose): click.echo('{}: {}{}\n {} - {}'.format(playback_status, (' ' if (not data['is_playing']) else ), music['track']['name'], music['artist']['long_name'], music['album']['name'])) if (verbose >= 1): click.echo('Track {} ({} / {})\nArtist {}\nAlbum {}\nStatus {} {}'.format(music['track']['name'], music['track']['progress'], music['track']['duration'], music['artist']['long_name'], music['album']['name'], playback_status, playback_str)) if (verbose >= 2): click.echo('\nDevice {} ({})\nURL {}'.format(data['device']['name'], data['device']['type'], music['track']['url'])) return
@click.command(options_metavar='[<options>]') @click.option('-v', '--verbose', count=True, help='Output more info (repeatable flag).') @click.option('--raw', is_flag=True, help='Output raw API response.') def status(verbose=0, raw=False, _override={}, _return_parsed=False): res = Spotify.request('me/player', method='GET') if (not res): raise NoPlaybackError if raw: if (verbose >= 0): import json click.echo(json.dumps(res)) return res data = {} data['is_podcast'] = (res['currently_playing_type'] == 'episode') if data['is_podcast']: raise PodcastNotSupported data['is_shuffle'] = res['shuffle_state'] data['repeat_state'] = res['repeat_state'] data['is_playing'] = res['is_playing'] data['device'] = {'name': res['device']['name'], 'type': res['device']['type'], 'volume': res['device']['volume_percent']} item = res['item'] context = parse_context(res['context']) data['music'] = {'context': context, 'track': parse_track(item), 'album': parse_album(item['album']), 'artist': parse_artists(item['artists'])} music = data['music'] music['track']['progress'] = format_duration_ms(res['progress_ms']) if _override: data.update(_override) for key in ['name', 'id', 'url']: music['artist'][key] = music['artist'][(key + 's')][0] music['artist'][('long_' + key)] = ', '.join(music['artist'][(key + 's')]) if (key != 'name'): music['artist'][('long_' + key)] = music['artist'][('long_' + key)].replace(' ', ) playback_status = ('Playing' if data['is_playing'] else 'Paused') playback_options = [] if (data['repeat_state'] == 'track'): playback_options.append('repeat [track]') elif (data['repeat_state'] == 'context'): playback_options.append('repeat') if data['is_shuffle']: playback_options.append('shuffle') playback_str = if data['is_playing']: playback_options_str = '{}'.format(('on {}'.format((' and '.join(playback_options) + ', ')) if playback_options else )) playback_str = '({}{}% volume)'.format(playback_options_str, data['device']['volume']) if _return_parsed: return data if (not verbose): click.echo('{}: {}{}\n {} - {}'.format(playback_status, (' ' if (not data['is_playing']) else ), music['track']['name'], music['artist']['long_name'], music['album']['name'])) if (verbose >= 1): click.echo('Track {} ({} / {})\nArtist {}\nAlbum {}\nStatus {} {}'.format(music['track']['name'], music['track']['progress'], music['track']['duration'], music['artist']['long_name'], music['album']['name'], playback_status, playback_str)) if (verbose >= 2): click.echo('\nDevice {} ({})\nURL {}'.format(data['device']['name'], data['device']['type'], music['track']['url'])) return<|docstring|>Describe the current playback session.<|endoftext|>
78df13d38e1c76d1f6521fe56b58407a2e322a5485562c9f51c0f3277edb490e
def initialize_weights(net): "\n initialize network\n note:It's different to initialize discriminator and classifier.\n For detail,please check the initialization of resnet and wgan-gp.\n " for m in net.modules(): if isinstance(m, nn.Conv2d): m.weight.data.normal_(0, 0.02) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.02) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
initialize network note:It's different to initialize discriminator and classifier. For detail,please check the initialization of resnet and wgan-gp.
networks/ops.py
initialize_weights
youngyzzZ/a-weakly-supervised-localization-and-segmentation-method
0
python
def initialize_weights(net): "\n initialize network\n note:It's different to initialize discriminator and classifier.\n For detail,please check the initialization of resnet and wgan-gp.\n " for m in net.modules(): if isinstance(m, nn.Conv2d): m.weight.data.normal_(0, 0.02) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.02) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
def initialize_weights(net): "\n initialize network\n note:It's different to initialize discriminator and classifier.\n For detail,please check the initialization of resnet and wgan-gp.\n " for m in net.modules(): if isinstance(m, nn.Conv2d): m.weight.data.normal_(0, 0.02) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.02) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()<|docstring|>initialize network note:It's different to initialize discriminator and classifier. For detail,please check the initialization of resnet and wgan-gp.<|endoftext|>
4499f42d4fdf2e0408f0b8fe86eda86b8aad5dc88773ef48426f7258cfd89ab2
def allowed_file(filename): "check the file name to avoid possible hack\n Arguments: uploaded file's name\n Return: rendered result page 'result.html'\n " return (('.' in filename) and (filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS))
check the file name to avoid possible hack Arguments: uploaded file's name Return: rendered result page 'result.html'
ReChord_frontend.py
allowed_file
oxy-compsci/reChord
1
python
def allowed_file(filename): "check the file name to avoid possible hack\n Arguments: uploaded file's name\n Return: rendered result page 'result.html'\n " return (('.' in filename) and (filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS))
def allowed_file(filename): "check the file name to avoid possible hack\n Arguments: uploaded file's name\n Return: rendered result page 'result.html'\n " return (('.' in filename) and (filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS))<|docstring|>check the file name to avoid possible hack Arguments: uploaded file's name Return: rendered result page 'result.html'<|endoftext|>
0596c9251781aaf4ce957e320d8a2530b70bdc0f8ad83b822d8dfdfaaadd1d23
@app.route('/') def form(): "render front page template\n Return: rendered front page 'index.html'\n " return render_template('index.html')
render front page template Return: rendered front page 'index.html'
ReChord_frontend.py
form
oxy-compsci/reChord
1
python
@app.route('/') def form(): "render front page template\n Return: rendered front page 'index.html'\n " return render_template('index.html')
@app.route('/') def form(): "render front page template\n Return: rendered front page 'index.html'\n " return render_template('index.html')<|docstring|>render front page template Return: rendered front page 'index.html'<|endoftext|>
21b67dfc02dcd2a5642b08bef1b973a269d5bd693b480522d66ee51601dfe8fa
@app.route('/documentation') def documentation(): "render front page template\n Return: rendered front page 'index.html'\n " return render_template('documentation.html')
render front page template Return: rendered front page 'index.html'
ReChord_frontend.py
documentation
oxy-compsci/reChord
1
python
@app.route('/documentation') def documentation(): "render front page template\n Return: rendered front page 'index.html'\n " return render_template('documentation.html')
@app.route('/documentation') def documentation(): "render front page template\n Return: rendered front page 'index.html'\n " return render_template('documentation.html')<|docstring|>render front page template Return: rendered front page 'index.html'<|endoftext|>
8c20431cfef0a6d0c279ebc506d52981486f290597a2dde12af5ae5c6078efee
@app.route('/', methods=['POST']) def form_post(): "the view function which return the result page by using the input pass to the back end\n Arguments: forms submitted in index.html\n Return: rendered result page 'result.html' by call on helper functions\n " if (request.form['submit'] == 'Search Snippet In Our Database'): path = 'database/MEI_Complete_examples' return search_snippet(path, request.form['text']) elif (request.form['submit'] == 'Search Terms In Our Database'): tag = request.form['term'] para = request.form['parameter'] path = 'database/MEI_Complete_examples' return search_terms(path, tag, para) elif (request.form['submit'] == 'Upload and Search Your Snippet'): with tempfile.TemporaryDirectory() as tmpdirname: try: path = upload_file('base_file', tmpdirname) return search_snippet(path, request.form['text']) except NameError as error_msg: return render_template('result.html', errors=str(error_msg)) elif (request.form['submit'] == 'Upload and Search Parameter'): tag = request.form['term'] para = request.form['parameter'] with tempfile.TemporaryDirectory() as tmpdirname: try: path = upload_file('base_file', tmpdirname) return search_terms(path, tag, para) except NameError as error_msg: return render_template('result.html', errors=str(error_msg)) else: abort(404) return None
the view function which return the result page by using the input pass to the back end Arguments: forms submitted in index.html Return: rendered result page 'result.html' by call on helper functions
ReChord_frontend.py
form_post
oxy-compsci/reChord
1
python
@app.route('/', methods=['POST']) def form_post(): "the view function which return the result page by using the input pass to the back end\n Arguments: forms submitted in index.html\n Return: rendered result page 'result.html' by call on helper functions\n " if (request.form['submit'] == 'Search Snippet In Our Database'): path = 'database/MEI_Complete_examples' return search_snippet(path, request.form['text']) elif (request.form['submit'] == 'Search Terms In Our Database'): tag = request.form['term'] para = request.form['parameter'] path = 'database/MEI_Complete_examples' return search_terms(path, tag, para) elif (request.form['submit'] == 'Upload and Search Your Snippet'): with tempfile.TemporaryDirectory() as tmpdirname: try: path = upload_file('base_file', tmpdirname) return search_snippet(path, request.form['text']) except NameError as error_msg: return render_template('result.html', errors=str(error_msg)) elif (request.form['submit'] == 'Upload and Search Parameter'): tag = request.form['term'] para = request.form['parameter'] with tempfile.TemporaryDirectory() as tmpdirname: try: path = upload_file('base_file', tmpdirname) return search_terms(path, tag, para) except NameError as error_msg: return render_template('result.html', errors=str(error_msg)) else: abort(404) return None
@app.route('/', methods=['POST']) def form_post(): "the view function which return the result page by using the input pass to the back end\n Arguments: forms submitted in index.html\n Return: rendered result page 'result.html' by call on helper functions\n " if (request.form['submit'] == 'Search Snippet In Our Database'): path = 'database/MEI_Complete_examples' return search_snippet(path, request.form['text']) elif (request.form['submit'] == 'Search Terms In Our Database'): tag = request.form['term'] para = request.form['parameter'] path = 'database/MEI_Complete_examples' return search_terms(path, tag, para) elif (request.form['submit'] == 'Upload and Search Your Snippet'): with tempfile.TemporaryDirectory() as tmpdirname: try: path = upload_file('base_file', tmpdirname) return search_snippet(path, request.form['text']) except NameError as error_msg: return render_template('result.html', errors=str(error_msg)) elif (request.form['submit'] == 'Upload and Search Parameter'): tag = request.form['term'] para = request.form['parameter'] with tempfile.TemporaryDirectory() as tmpdirname: try: path = upload_file('base_file', tmpdirname) return search_terms(path, tag, para) except NameError as error_msg: return render_template('result.html', errors=str(error_msg)) else: abort(404) return None<|docstring|>the view function which return the result page by using the input pass to the back end Arguments: forms submitted in index.html Return: rendered result page 'result.html' by call on helper functions<|endoftext|>
ae5969792b44e44c49f6b96d892b9b560597d0d21c7c38641a3f3256031c396e
def get_mei_from_folder(path): 'gets a list of MEI files from a given folder path\n Arguments: path [string]: absolute or relative path to folder\n Returns: all_mei_files: List<file>: list of mei files in path\n ' return [((path + '/') + filename) for filename in os.listdir(path) if (filename.endswith('.mei') or filename.endswith('.xml'))]
gets a list of MEI files from a given folder path Arguments: path [string]: absolute or relative path to folder Returns: all_mei_files: List<file>: list of mei files in path
ReChord_frontend.py
get_mei_from_folder
oxy-compsci/reChord
1
python
def get_mei_from_folder(path): 'gets a list of MEI files from a given folder path\n Arguments: path [string]: absolute or relative path to folder\n Returns: all_mei_files: List<file>: list of mei files in path\n ' return [((path + '/') + filename) for filename in os.listdir(path) if (filename.endswith('.mei') or filename.endswith('.xml'))]
def get_mei_from_folder(path): 'gets a list of MEI files from a given folder path\n Arguments: path [string]: absolute or relative path to folder\n Returns: all_mei_files: List<file>: list of mei files in path\n ' return [((path + '/') + filename) for filename in os.listdir(path) if (filename.endswith('.mei') or filename.endswith('.xml'))]<|docstring|>gets a list of MEI files from a given folder path Arguments: path [string]: absolute or relative path to folder Returns: all_mei_files: List<file>: list of mei files in path<|endoftext|>
1d5f5db92350e3629b25262adeae11a120189a06929c126d8cb03c8650fa1824
def search_snippet(path, snippet): "search the snippet from the given database\n Arguments:\n snippet of xml that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n " xml = BytesIO(snippet.encode()) error_msg = '' try: (input_xml_tree, _) = prepare_tree(xml) named_tuples_ls = snippet_search_folder(path, input_xml_tree) if named_tuples_ls: return render_template('result.html', origins=named_tuples_ls) else: error_msg = 'No matched snippet found, maybe try something else?' return render_template('result.html', nomatch=error_msg) except (etree.XMLSyntaxError, ValueError): error_msg = 'Invalid MEI snippet inputs. Please double check the source and try it again!' except KeyError: error_msg = 'Invalid upload file. Please double check the source and try it again!' return render_template('result.html', errors=error_msg)
search the snippet from the given database Arguments: snippet of xml that want to search for tree of xml base that needed to be searched in Return: rendered result page 'result.html'
ReChord_frontend.py
search_snippet
oxy-compsci/reChord
1
python
def search_snippet(path, snippet): "search the snippet from the given database\n Arguments:\n snippet of xml that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n " xml = BytesIO(snippet.encode()) error_msg = try: (input_xml_tree, _) = prepare_tree(xml) named_tuples_ls = snippet_search_folder(path, input_xml_tree) if named_tuples_ls: return render_template('result.html', origins=named_tuples_ls) else: error_msg = 'No matched snippet found, maybe try something else?' return render_template('result.html', nomatch=error_msg) except (etree.XMLSyntaxError, ValueError): error_msg = 'Invalid MEI snippet inputs. Please double check the source and try it again!' except KeyError: error_msg = 'Invalid upload file. Please double check the source and try it again!' return render_template('result.html', errors=error_msg)
def search_snippet(path, snippet): "search the snippet from the given database\n Arguments:\n snippet of xml that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n " xml = BytesIO(snippet.encode()) error_msg = try: (input_xml_tree, _) = prepare_tree(xml) named_tuples_ls = snippet_search_folder(path, input_xml_tree) if named_tuples_ls: return render_template('result.html', origins=named_tuples_ls) else: error_msg = 'No matched snippet found, maybe try something else?' return render_template('result.html', nomatch=error_msg) except (etree.XMLSyntaxError, ValueError): error_msg = 'Invalid MEI snippet inputs. Please double check the source and try it again!' except KeyError: error_msg = 'Invalid upload file. Please double check the source and try it again!' return render_template('result.html', errors=error_msg)<|docstring|>search the snippet from the given database Arguments: snippet of xml that want to search for tree of xml base that needed to be searched in Return: rendered result page 'result.html'<|endoftext|>
e73f4d9679cddc7cd5680152984451556a473e21f010881f0e1b54b9eef84873
def search_terms(path, tag, para): " search terms in the database\n Arguments:\n tags of term that want to search for\n para(meters) of tags that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n " error_msg = '' try: named_tuples_ls = text_box_search_folder(path, tag, para) if named_tuples_ls: return render_template('result.html', origins=named_tuples_ls) else: error_msg = 'No matched term found, maybe try something else?' return render_template('result.html', nomatch=error_msg) except KeyError: error_msg = 'Invalid upload file. Please double check the source and try it again!' return render_template('result.html', errors=error_msg)
search terms in the database Arguments: tags of term that want to search for para(meters) of tags that want to search for tree of xml base that needed to be searched in Return: rendered result page 'result.html'
ReChord_frontend.py
search_terms
oxy-compsci/reChord
1
python
def search_terms(path, tag, para): " search terms in the database\n Arguments:\n tags of term that want to search for\n para(meters) of tags that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n " error_msg = try: named_tuples_ls = text_box_search_folder(path, tag, para) if named_tuples_ls: return render_template('result.html', origins=named_tuples_ls) else: error_msg = 'No matched term found, maybe try something else?' return render_template('result.html', nomatch=error_msg) except KeyError: error_msg = 'Invalid upload file. Please double check the source and try it again!' return render_template('result.html', errors=error_msg)
def search_terms(path, tag, para): " search terms in the database\n Arguments:\n tags of term that want to search for\n para(meters) of tags that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n " error_msg = try: named_tuples_ls = text_box_search_folder(path, tag, para) if named_tuples_ls: return render_template('result.html', origins=named_tuples_ls) else: error_msg = 'No matched term found, maybe try something else?' return render_template('result.html', nomatch=error_msg) except KeyError: error_msg = 'Invalid upload file. Please double check the source and try it again!' return render_template('result.html', errors=error_msg)<|docstring|>search terms in the database Arguments: tags of term that want to search for para(meters) of tags that want to search for tree of xml base that needed to be searched in Return: rendered result page 'result.html'<|endoftext|>
b124a6da568118ad3565b42d9f98b136023aa2705390b2f9ca82836b5d45f89d
def upload_file(name_tag, tmpdirname): "pass the upload files and store them in uploads folder's unique sub-folder\n Arguments: name_tag that used in html\n Return: upload path name\n " if ('base_file' not in request.files): flash('No file part') return redirect(request.url) else: files = request.files.getlist(name_tag) for file in files: if (file.filename == ''): flash('No selected file') return redirect(request.url) elif file: if allowed_file(file.filename): file.save(os.path.join(tmpdirname, secure_filename(file.filename))) else: raise NameError((file.filename + ' is not a allowed name or the file extension is not .mei or .xml.')) return tmpdirname
pass the upload files and store them in uploads folder's unique sub-folder Arguments: name_tag that used in html Return: upload path name
ReChord_frontend.py
upload_file
oxy-compsci/reChord
1
python
def upload_file(name_tag, tmpdirname): "pass the upload files and store them in uploads folder's unique sub-folder\n Arguments: name_tag that used in html\n Return: upload path name\n " if ('base_file' not in request.files): flash('No file part') return redirect(request.url) else: files = request.files.getlist(name_tag) for file in files: if (file.filename == ): flash('No selected file') return redirect(request.url) elif file: if allowed_file(file.filename): file.save(os.path.join(tmpdirname, secure_filename(file.filename))) else: raise NameError((file.filename + ' is not a allowed name or the file extension is not .mei or .xml.')) return tmpdirname
def upload_file(name_tag, tmpdirname): "pass the upload files and store them in uploads folder's unique sub-folder\n Arguments: name_tag that used in html\n Return: upload path name\n " if ('base_file' not in request.files): flash('No file part') return redirect(request.url) else: files = request.files.getlist(name_tag) for file in files: if (file.filename == ): flash('No selected file') return redirect(request.url) elif file: if allowed_file(file.filename): file.save(os.path.join(tmpdirname, secure_filename(file.filename))) else: raise NameError((file.filename + ' is not a allowed name or the file extension is not .mei or .xml.')) return tmpdirname<|docstring|>pass the upload files and store them in uploads folder's unique sub-folder Arguments: name_tag that used in html Return: upload path name<|endoftext|>
670063089fa19f2910a2b64a67d074f9cf3cb3495f26a3b35d32ab44fa15e09e
@bp.route('/healthz') def healthz(): 'Status check to verify the service and required dependencies are still working.\n\n This could be thought of as a heartbeat for the service\n ' try: db.session.execute(SQL) except exc.SQLAlchemyError as db_exception: current_app.logger.error(('DB connection pool unhealthy:' + str(db_exception))) return ({'message': 'api is down'}, 500) except Exception as default_exception: current_app.logger.error(('DB connection pool query failed:' + str(default_exception))) return ({'message': 'api is down'}, 500) return (jsonify({'message': 'api is healthy'}), 200)
Status check to verify the service and required dependencies are still working. This could be thought of as a heartbeat for the service
mhr_api/src/mhr_api/resources/v1/ops.py
healthz
cameron-freshworks/ppr
0
python
@bp.route('/healthz') def healthz(): 'Status check to verify the service and required dependencies are still working.\n\n This could be thought of as a heartbeat for the service\n ' try: db.session.execute(SQL) except exc.SQLAlchemyError as db_exception: current_app.logger.error(('DB connection pool unhealthy:' + str(db_exception))) return ({'message': 'api is down'}, 500) except Exception as default_exception: current_app.logger.error(('DB connection pool query failed:' + str(default_exception))) return ({'message': 'api is down'}, 500) return (jsonify({'message': 'api is healthy'}), 200)
@bp.route('/healthz') def healthz(): 'Status check to verify the service and required dependencies are still working.\n\n This could be thought of as a heartbeat for the service\n ' try: db.session.execute(SQL) except exc.SQLAlchemyError as db_exception: current_app.logger.error(('DB connection pool unhealthy:' + str(db_exception))) return ({'message': 'api is down'}, 500) except Exception as default_exception: current_app.logger.error(('DB connection pool query failed:' + str(default_exception))) return ({'message': 'api is down'}, 500) return (jsonify({'message': 'api is healthy'}), 200)<|docstring|>Status check to verify the service and required dependencies are still working. This could be thought of as a heartbeat for the service<|endoftext|>